Session::flash is not working in Laravel version 5.2.27 - forms

I am trying to display a success message upon form submit in Laravel.
However, it doesn't work.
I've added use Session; at the top of the controller file, the routes are in the middleware and the configuration in config/session.php is the default one.
My controller function is able to save in the database without any problem :
public function store(Request $request)
{
$post = new Post;
$post->title = $request->title;
$post->description = $request->description;
$post->slug = $request->slug;
$post->body = $request->body;
$post->save();
Session::flash('success', 'SUCCESS MESSAGE GOES HERE');
return redirect()->route('posts.show', $post->id);
}
here is my template file :
#if(Session::has('success'))
<div class="alert-box success">
<h2>{{ Session::get('success') }}</h2>
</div>
#endif
My routes :
Route::group(['middleware' => ['web']], function() {
Route::get('/', 'PagesController#getIndex');
Route::resource('posts','PostController');
});
Is see there is no success in the session file. I cannot figure out why exactly :
a:4:{s:6:"_token";s:40:"EntXIr9tkqAcKarDZhaNxKb6RfcFdFV9ZtF6W7kU";s:9:"_previous";a:1:{s:3:"url";s:30:"http://localhost:8000/posts/35";}s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}s:9:"_sf2_meta";a:3:{s:1:"u";i:1459467699;s:1:"c";i:1459467699;s:1:"l";s:1:"0";}}
Someone can help me figure out what the problem is?

The web middleware no longer needs to be explicitly applied to routes in your routes.php file. It is now silently applied to routes within app/Providers/RouteServiceProvider.php, as per this change in Laravel 5.2.27
Previously you would be required to explicitly apply the web middleware to routes like so:
Route::group(['middleware' => ['web']], function () {
Route::get('/', function () {
return view('welcome');
});
});
The above can now be achieved like so:
Route::get('/', function () {
return view('welcome');
});

Make sure the route is using the "web" middleware to access session data.
Route::group(['middleware' => 'web'], function () {
Route::get('foo', 'FooController#bar'); // session data should be available here
});

Related

How to use dynamic page titles in sails.js >v1.0?

For the last few days I was looking for a viable solution in order to optimize html page titles <title>SOME_TITLE</title> within sails.js layout files, like layout.ejs, that by default use a static page title.
Obviously, it would be way better to have dynamic page titles, e.g. Dashboard, Shopping Cart, etc...
Other people were looking for this answer before and got answers for prior sails versions in Solution 1, Solution 2 and Solution 3.
Unfortunately, none of them seem to be appropriate for the latest version of sails.js (as of this post).
Solution 1 was leading in the right direction and suggested what I was looking for. But you had to define a title for every controller and pass it into the view. Otherwise you will get
title is not defined at eval
So how to define a local variable that is accessible in each controller/view by default?
So one working complete solution for the current sails.js version is the following:
In your layout.ejs file define a dynamic page title like this
<head>
<title>
<%= title %>
</title>
...
</head>
...
Create a new custom hook, e.g. api/hooks/dynamic-page-title/index.js
module.exports = function dynamicPageTitleHook(sails) {
return {
routes: {
/**
* Runs before every matching route.
*
* #param {Ref} req
* #param {Ref} res
* #param {Function} next
*/
before: {
'/*': {
skipAssets: true,
fn: async function(req, res, next){
// add page title variable to each response
if (req.method === 'GET') {
if (res.locals.title === undefined) {
res.locals.title = 'plusX';
}
}
return next();
}
}
}
}
};
};
Now overwrite the page title in every controller that should use a custom page title, e.g. view-login.ejs
module.exports = {
friendlyName: 'View login',
description: 'Display "Login" page.',
exits: {
success: {
viewTemplatePath: 'pages/entrance/login',
},
redirect: {
description: 'The requesting user is already logged in.',
responseType: 'redirect'
}
},
fn: async function (inputs, exits) {
if (this.req.me) {
throw {redirect: '/'};
}
return exits.success({title: 'Login'});
}
};
module.exports = {
friendlyName: 'View homepage or redirect',
description: 'Display or redirect to the appropriate homepage, depending on login status.',
exits: {
success: {
statusCode: 200,
description: 'Requesting user is a guest, so show the public landing page.',
viewTemplatePath: 'pages/homepage'
},
redirect: {
responseType: 'redirect',
description: 'Requesting user is logged in, so redirect to the internal welcome page.'
},
},
fn: async function () {
if (this.req.me) {
throw {redirect:'/welcome'};
}
return {title: 'Home page'};
}
};
e.g: return (title: 'Home page')
I use version 1.4 of sails
I have add to the file layout.ejs the following code
<% if (typeof pagetitle=="undefined"){%>
<title>write your default title</title>
<% }else{%>
<title><%= pagetitle %></title>
<%}%>
<% if (typeof pagemetadescription=="undefined"){%>
<mеtа nаmе="dеѕсrірtіоn" соntеnt="write your default metadescription"></mеtа>
<% }else{%>
<mеtа nаmе="dеѕсrірtіоn" соntеnt="<%= pagemetadescription %>"></mеtа>
<%}%>
If in controller, i return variable pagetitle or pagedescription, they will be add to layout. Otherwise, the default value will be print.

signup to Laravel from a different server

I want to show a signup form on a website but then when user hits submit, the form data will be posted to a Laravel app (on a different server) for registration.
So far, laravel stops it throwing the CSRF not found exception. Any idea how to work around it ?
If both applications are yours?
You can create a new middleware group:
protected $middlewareGroups = [
'web' => [
...
],
'remote-login' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
// \App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
Commenting/removing/disabling the VerifyCsrfToken middleware. Then map it to a new file:
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
Route::middleware('remote-login')
->namespace($this->namespace)
->group(base_path('routes/remote-login.php'));
}
Then in your routes/remote-login.php, you better create a non-trivial login route:
Route::group(['prefix' => 'remote-login'], function () {
Route::get('/auth/8g7h6jk5l4oA/', function () {
dd('do you authentication');
});
});
Antonio's approach will work, but it's easier to just add the routes you don't want protected by the CSRF middleware to the $except array in app/Http/Middleware/VerifyCsrfToken.php.

how to use third party javascript code in magento2 payment?

I am facing problem while adding third party javascript code in my payment module in magento2.
following is my code.
define(
[
'Magento_Payment/js/view/payment/cc-form',
'jquery',
'Vendorname_Modulename/js/stsdk'
'Magento_Payment/js/model/credit-card-validation/validator'
],
function (Component, $, STDirect) {
'use strict';
return Component.extend({
defaults: {
template: 'Vendorname_Modulename/payment/module-form'
},
getCode: function() {
return 'vendor_module';
},
isActive: function() {
return true;
},
validate: function() {
STDirect.setupSDK('23842', "testnumber", 'typeofenv');
STDirect.card.createToken(number, exp_month, exp_year, ccv, function (result) {
var secretkey = '';
if(result.status==0){
secretkey = result.card.secretkey;
}
document.write(JSON.stringify(result));
alert(secretkey);
});
var $form = $('#' + this.getCode() + '-form');
return $form.validation() && $form.validation('isValid');
}
});
}
);
I have tried above code, stsdk.js is loaded in network but it gives me following error :
ReferenceError: STDirect is not defined
STDirect.setupSDK('23842', "testnumber", 'sandbox');
I have also checked by load this js file in header but same error appear.
My question is how to execute third party javascript code in define scope.
I tried with the custom javascript function after define function but it is also not callable from validate function and when I use require[] function within define function it raise error.
I appreciate any help.

Laravel 5.4 Locale restores to default when using redirect()

I'm struggling with the Laravel's locale on Fresh new Project. I googled many times, but they didn't solve my problem.
Then I followed locale in laravel 5.4 returns to the pervious locale after refresh source, but it works only when I call pages by view
return view('home');
And it does not work when I use routes
return redirect()->route('home');
Here are my files:
web.php
Route::get('/lang/{locale}', function ($locale) {
App::setLocale($locale);
Session::put('locale', $locale);
//return view('home'); ###### This one works
return redirect()->route('home'); ###### Where as this does NOT work
});
Route::get('/', function () {
return view('welcome');
});
Route::get('/home', 'HomeController#index')->name('home');
home.blade.php
<div class="panel-body">
You are logged in!
{{__('auth.success')}}
<br>
Rus
<br>
Kgz
</div>
ChangeLocale.php Middleware (I call it for every request of pages)
public function handle($request, Closure $next)
{
if(Session::has('locale')) {
app()->setLocale(Session::get('locale'));
}
return $next($request);
}
Thanks in advance ;)
Ok, after I changed
Route::get('/home', 'HomeController#index')->name('home');
to
Route::get('/home', 'HomeController#index')->name('home')->middleware('changeLocale');
It started to work.
So, why my Middleware, is not working?
Should I assign middleware seperately to all my routes?
You may add your changeLocale middleware to web group in app/Http/Kernel.php:
protected $middlewareGroups = [
'web' => [
...
\Your\ChangeLocateMiddleware::class
],
...
]
As you may see in app/Providers/RouteServiceProvider.php, this middleware group applies to all your web routes.

JSON object parsing error using jQuery Form Plugin

Environment: JQuery Form Plugin, jQuery 1.7.1, Zend Framework 1.11.11.
Cannot figure out why jQuery won't parse my json object if I specify an url other than a php file.
The form is as follows:
<form id="imageform" enctype="multipart/form-data">
Upload your image <input type="file" name="photoimg" id="photoimg" />
<input type="submit" id ="button" value="Send" />
</form>
The javascript triggering the ajax request is:
<script type="text/javascript" >
$(document).ready(function() {
var options = {
type: "POST",
url: "<?php $this->baseURL();?>/contact/upload",
dataType: 'json',
success: function(result) {
console.log(result);
},
error: function(ob,errStr) {
console.log(ob);
alert('There was an error processing your request. Please try again. '+errStr);
}
};
$("#imageform").ajaxForm(options);
});
</script>
The code in my zend controller is:
class ContactController extends BaseController {
public function init() {
/* Initialize action controller here */
}
public function indexAction() {
}
public function uploadAction() {
if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$image = $_FILES['photoimg']['tmp_name'];
$im = new imagick($image);
$im->pingImage($image);
$im->readImage($image);
$im->thumbnailImage(75, null);
$im->writeImage('userImages/test/test_thumb.jpg');
$im->destroy();
echo json_encode(array("status" => "success", "message" => "posted successfully"));
}
else
echo json_encode(array("status" => "fail", "message" => "not posted successfully"));
}
}
When I create an upload.php file with the above code, and modify the url from the ajax request to
url: "upload.php",
i don't run into that parsing error, and the json object is properly returned. Any help to figure out what I'm doing wrong would be greatly appreciated! Thanks.
You need either to disable layouts, or using an action helper such as ContextSwitch or AjaxContext (even better).
First option:
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout->disableLayout();
And for the second option, using AjaxContext, you should add in your _init() method:
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('upload', 'json')
->initContext();
This will disable automatically disable layouts and send a json header response.
So, instead of your two json_encode lines, you should write:
$this->status = "success";
$this->message = "posted successfully";
and
$this->status = "fail";
$this->message = "not posted successfully";
In order to set what to send back to the client, you simply have to assign whatever content you want into view variables, and these variables will be automatically convert to json (through Zend_Json).
Also, in order to tell your controller which action should be triggered, you need to add /format/json at the end of your URL in your jQuery script as follow:
url: "<?php $this->baseURL();?>/contact/upload/format/json",
More information about AjaxContext in the manual.
Is the Content-type header being properly set as "application/json" when returning your JSON?