Laravel set cookie in API not set - php

I using laravel 5 as Rest API, and I want to set a cookie in controller:
return response()->json(['success' => $data], $this-> successStatus)->cookie('name', 'myvalue');
this return with response cookie successfully, but can not access in front, I also used:
Cookie::queue($name, $value);
Or
Cookie::queue(Cookie::make('cookieName', 'value'));
Or all way in google, stackoverflow, but none of these set cookie in browser, I need to set http only cookie in browser via laravel controller. how can i do this?
I also used php cookie, no success

Cookies will be set on web middleware group only not api. According to docs, Laravel comes with web and api middleware groups that contain common middleware you may want to apply to your web UI and API routes:
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
//...
],
'api' => [
'throttle:60,1',
'auth:api',
],
];
As you can see, EncryptCookies and AddQueuedCookiesToResponse middlewares are applied to web group only but not api.
// This works and sets encrypted cookie on response.
Route::group(['middleware' => ['web']], function () {
return response()
->cookie('name', 'value');
});
// This won't set cookie on response.
Route::group(['middleware' => ['api']], function () {
return response()
->cookie('name', 'value');
});

You may use
$response = new \Illuminate\Http\JsonResponse(['success' => $data], $this->successStatus);
$response->withCookie(cookie($cookieName, $cookieVal, 45000));
return $response;
Illuminate\Http\JsonResponse

Normally we cannot set cookies in API route due to EncryptCookies and AddQueuedCookiesToResponse not being added by default. So we have to add those classes in the kernel with API middleware.
'api' => [
//my change
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
//end of my change
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
Then we can set and get a cookie.

Related

Laravel API + Sanctum + Angular + SSO (SAML) - How to build a Laravel 7/8 API with front-end in Angular 11 and SAML auth

I need to turn my laravel api + angular sanctum authentication into a SAML authentication.
I've noticed that I need to use a laravel plugin like laravel-saml2 or laravel-saml2. (Yes... Same name but different plugins)
I intend to use OKTA because I am already using it to authenticate in my Stack ELK.
But my biggest doubt is: Since my front-end (angular) is communicating to my backend through a stateless API (sanctum), is it possible to implement a SSO SAML to authentication?
I would truly appreciate if anyone could show me how it is possible. And in case it is not, how could my app be rethinked to achieve this goal.
Thanks in advance.
i had the same requirement working according to the next:
Laravel 8 with sanctum (the key to make use of SANCTUM_STATEFUL_DOMAINS)
Make sure your Angular URL application is configured in SANCTUM_STATEFUL_DOMAINS (.env)
like
SANCTUM_STATEFUL_DOMAINS=localhost:4200
laravel-saml2 (https://github.com/aacotroneo/laravel-saml2) configured accorded to documentation.
In app/Http/Kernel.php
protected $middlewareGroups = [
'web' => [
\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,
],
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'saml' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
],
];
And
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
// Add SAML Middleware
'auth.saml' => \App\Http\Middleware\SAMLAuthenticated::class,
];
In app/Providers/EventServiceProvider.php
namespace App\Providers;
use Aacotroneo\Saml2\Events\Saml2LoginEvent;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* #var array
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];
/**
* Register any events for your application.
*
* #return void
*/
public function boot()
{
Event::listen('Aacotroneo\Saml2\Events\Saml2LogoutEvent', function ($event) {
Auth::logout();
Session::save();
});
Event::listen('Aacotroneo\Saml2\Events\Saml2LoginEvent', function (Saml2LoginEvent $event) {
$messageId = $event->getSaml2Auth()->getLastMessageId();
// Add your own code preventing reuse of a $messageId to stop replay attacks
$user = $event->getSaml2User();
$userData = [
'id' => $user->getUserId(),
'attributes' => $user->getAttributes(),
'assertion' => $user->getRawSamlAssertion()
];
//If it not exists, create a Laravel User from an Authenticated SAML account
$laravelUser = User::firstOrCreate([
'email' => $user->getAttribute("urn:oid:0.9.2342.19200300.100.1.3")[0],
'name' => $user->getAttribute("urn:oid:0.9.2342.19200300.100.1.1")[0],
], ['password' => Hash::make('CREATE_DUMMY_NOT_BEING_USED')]);
Auth::login($laravelUser); // AUTHENTICATION WITHIN LARAVEL
});
}
}
Next, I've created a new Middleware (/app/Http/Middleware/SAMLAuthenticated.php)
namespace App\Http\Middleware;
use Aacotroneo\Saml2\Saml2Auth;
use Closure;
use Illuminate\Support\Facades\Auth;
class SAMLAuthenticated
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null ...$guards
* #return mixed
*/
public function handle($request, Closure $next, ...$guards)
{
if (!Auth::check())
{
if ($request->ajax())
{
return response('Unauthorized.', 401); // Or, return a response that causes client side js to redirect to '/routesPrefix/myIdp1/login'
}
else
{
// VERY IMPORTANT WHEN ANGULAR REQUEST
$retUrl = 'http://localhost:4200';
$saml2Auth = new Saml2Auth(Saml2Auth::loadOneLoginAuthFromIpdConfig('corsisa'));
return $saml2Auth->login($retUrl);
}
}
return $next($request);
}
}
You can test SAML Auth (/app/routes/web.php)
Route::middleware('auth.saml')->group(function () {
//protected routes go here
Route::get('/', function () {
return view('welcome');
});
});
// Also, you can map login & logout
Route::redirect('/login', '/saml2/<idp_name>/login')->name('login');
Route::redirect('/logout', '/saml2/<idp_name>/logout')->name('logout');
At this point, laravel application should redirect to SAML2 Login page.
Configure API routes, (app/routes/api.php:)
Route::middleware('auth.saml')->group(function () {
// Secured routes go here
Route::get('/me' ,function (Request $request) { return $request->user(); });
Route::get('/login' ,function (Request $request) {
return redirect('http://localhost:4200');
});
});
In Angular application, I use the next steps:
First, Make an HTTP Request to "http://laravel_api/api/me"
For example:
this.http.get<User>(URLHelper.concat(environment.API_BASE_URL, "api", "me"), { withCredentials: true, setHeaders: {"X-Requested-With": "XMLHttpRequest"} })
If response is 401, (UNAUTHORIZED), then will be redirected to "http://laravel_api/api/login"
window.location.replace(URLHelper.concat(environment.API_BASE_URL, "api", "login"), { withCredentials: true, setHeaders: {"X-Requested-With": "XMLHttpRequest"} })
Redirection will send the user to the SAML2 Login Page and then redirect back to Angular frontend. (by SAMLAuthenticated middleware )
So when redirect back is completed, Angular makes a new request to http://laravel_api/api/me, this time with an Auth Cookie generated by Sanctum.
Surely this procedure can be improved, but you can use it as a working starting point.
Regards

Flash data not being written to session

Im using Laravel 7.12.0 and my flash session data doesn't appear to be working at all either using
request()->session()->flash('status', 'Task was successful!');
or
return redirect()->route('home')->with('status', "Task was successful");
I am using Debugbar as well as dd'ing the page to check session data.
I also know that the web middleware is being used.
session()->put() still works so I know putting data into the session aren't entirely broken but flash data does not seem to work at all. This is a fresh installation so I am struggling to see what could be wrong?
Web.php
Auth::routes();
Route::get('/', 'HomeController#index')->name('home');
Route::group(['middleware' => ['auth']], function () {
Route::resource('polls', 'PollController');
Route::post('polls/vote', 'PollController#vote')->name('polls.vote');
});
Route::resource('api/polls', 'API\PollController');
Part of RouteServiceProvider.php
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* #return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
Web Middleware group in kernel.php
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\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,
],
'api' => [
'throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function index()
{
dd(request()->session()->all());
}
}
What is in the session from my HomeController#index after being redirected.
"_token" => "pbZJgfC6XNG2eTqlcGADm68NqhjOHI16rWe4U1bt"
"_previous" => array:1 [▼
"url" => "http://127.0.0.1:8000"
]
"_flash" => array:2 [▼
"old" => []
"new" => []
]
"url" => []
"login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d" => 1
]
Thanks
Seems as though this has to do with the hosting environment. I was able to reproduce the issue on my local machine when using http://127.0.0.1:8000. After switching to http://localhost:8000 the sessions started to persist as expected with both ->flash and ->with.

Laravel 5.4 Dingo Route Binding

I'm attempting to bind a function to the routing so it takes effect globally.
Basically I'm using Hashids to obfuscate the IDs, and want to be able to decode the ID on the route level so I don't need to do it everywhere the ID is uses in different controllers.
I've attempted to do the following at the top of the api routes file:
api.php
<?php
use Dingo\Api\Routing\Router;
use Hashids\Hashids;
Route::bind('id', function ($id) {
return Hasher::decode($id);
});
/** #var Router $api */
$api = app(Router::class);
But it doesn't seem to have any effect.
I have a couple of routes that use the ID I want to decode at the bottom of the routes file:
$api->get('leads/{id}', 'App\\Api\\V1\\Controllers\\LeadController#show');
$api->put('leads/update/{id}', 'App\\Api\\V1\\Controllers\\LeadController#update');
Really at a loss as to how to get this to work, I've tried using $api->bind and others but they all call undefined functions.
Sure this is an easy thing, but I'm just starting out with Laravel so this is a bit beyond me at this point.
Many thanks!
Based on the hint that Serge gave me, I've attempted to move this functionality into Middleware, but still due to a full lack of understanding, this isn't working.
I have the following middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Junity\Hashids\Facades\Hashids;
class DecodeHashids
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if($request->has('id'))
$request->id = Hasher::decode($request->id);
return $next($request);
}
}
I've added it to Kernal.php:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
'decode',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'jwt.auth' => GetUserFromToken::class,
'jwt.refresh' => RefreshToken::class,
'decode' => \App\Http\Middleware\DecodeHashids::class,
];
}
and added it in the api routes file as so:
$api->group(['middleware' => 'jwt.auth'], function(Router $api) {
$api->get('protected', function() {
return response()->json([
'message' => 'Access to protected resources granted! You are seeing this text as you provided the token correctly.'
]);
});
$api->get('refresh', [
'middleware' => 'jwt.refresh',
function() {
return response()->json([
'message' => 'By accessing this endpoint, you can refresh your access token at each request. Check out this response headers!'
]);
}
]);
$api->group(['middleware' => 'decode'], function(Router $api) {
$api->get('leads/{id}', 'App\\Api\\V1\\Controllers\\LeadController#show');
});
I get no errors, but the ID is not decoded when it passes through to the controller.
Thanks to the help from Serge, I managed to complete the Middleware.
Middleware as below, it updates the Route ID Parameter with the decoded value, and this Middleware is added to the Kernal.
<?php
namespace App\Http\Middleware;
use Closure;
use Hashids;
class DecodeHashids
{
public function handle($request, Closure $next)
{
if($request->route()->parameters('id'))
$request->route()->setParameter('id', Hashids::decode($request->id));
return $next($request);
}
}
Then in the API route file, I added a new group that uses the 'decode' Middleware:
$api->group(['middleware' => 'decode'], function(Router $api) {
$api->get('leads/{id}', 'App\\Api\\V1\\Controllers\\LeadController#show');
});
Can then of course add as many routes to this group where parameters need decoded.
Thanks Serge and the Laravel community for the help and responses on here and other sites. Hopefully this will help others.

Laravel 5.2 Sessions not persisting

I've searched a lot before posting and every 'solution' that I've found did not work.
I can't get a session value from a different route than the current one.
Routes.php
Route::group(['middleware' => 'web', 'prefix' => 'blog', 'namespace' => 'Modules\Blog\Http\Controllers'], function()
{
Route::get('/','PostController#index');
Route::get('/home',['as' => 'home', 'uses' => 'PostController#index']);
Route::get('auth/login', 'Auth\AuthController#showLoginForm');
Route::post('auth/login', 'Auth\AuthController#login');
Route::group(['middleware' => 'blog.auth'], function(){
Route::get('/admin',['as'=>'dashboard','uses'=>'AdminController#index']);
});
});
Kernel.php
protected $middlewareGroups = [
'web' => [
\ommitedbutcorrect\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class
],
'admin' => [
\Modules\Admin\Http\Middleware\ControllerResolver::class,
],
'admin.auth' => [
\Modules\Admin\Http\Middleware\AdminAuthenticate::class,
],
'blog.auth' => [
\Modules\Blog\Http\Middleware\BlogAuthenticate::class,
],
'api' => [
'throttle:60,1',
],
];
AuthController.php
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/blog/admin/';
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
public function login()
{
dd(\Session::get('foo'));
$userdata = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if (\Auth::attempt($userdata)) {
\Session::save();
return redirect($this->redirectTo);
}
else{
return 'f*ck';
}
}
public function showLoginForm()
{
\Session::put('foo', 'bar');
return view('blog::Admin.login');
}
Chmod 777 on Storage and Bootstrap folders, session driver database.
It seems that the session is creating itself every time with the request that would explain why I can't get the the value with Session:get('foo') which now returns null.
I wasted 3 days on this already :/.
Would appreciate the help, if you guys need more details / code just say the word.
I'm not sure why Laravel ships with session middleware in the wrong array, but move the StartSession middleware into the protected middleware group
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
];
Fixed by clearing the cache with php artisan cache:clear
I got my project from another person so no matter what changes I did, it used the cached settings(in this case it was using DB sessions and I wanted to use file-based sessions)
I guess it was because you use modules instead of the default structure laravel provided.
all routes bind with the web middleware by default in laravel 5.2, however, you use modules and each module has a separated routes.php file. You have to manually bind the routes with the web middleware again otherwise, your session will lost.
That was what I did when I met a similar problem. Please let me know my understanding is correct.
If you're on Laravel >= v5.2.27, you need to remove the web middleware from your app/Http/routes.php file. As of v5.2.27, all routes inside the app/Http/routes.php file are already included in the web middleware group, so adding the middleware again inside the file messes with the sessions.
What new Service Provider signed up?

Laravel 5.2 $errors not appearing in Blade

So I'm following along with the Laravel 5 fundamentals tutorial and I am stuck on the form validation. I have followed along exactly with the tutorial but I am getting a Undefined variable: errors in my create articles view.
In the tutorial I am following and what I have found online they say the errors variable is always there in the blade file for you to use so I don't know what i am doing wrong?
Any help would be appreciated! loving Laravel except for this error!
View
#if($errors->any())
<ul class="alert alert-danger">
#foreach($errors->any() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
#endif
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Http\Requests;
use App\Http\Requests\UserRequest as UserRequest;
// use App\Http\Requests\CreateArticleRequest as CreateArticleRequest;
use App\Http\Controllers\Controller;
use Illuminate\View\Middleware\ErrorBinder;
class UserController extends Controller
{
public function create(){
return view('pages.signUp');
}
public function store(UserRequest $request){
User::create($request->all());
return 'the user has been registered!';
return view('user.profile');
}
}
Request validation
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class UserRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email',
'country' => 'required',
'password' => 'required|min:6',
'confirm_password' => 'required|same:password',
'height' => 'required',
'weight' => 'required',
];
}
}
This is a breaking problem with the 5.2 upgrade. What's happening is the middleware which is responsible for making that errors variable available to all your views is not being utilized because it was moved from the global middleware to the web middleware group.
There are two ways to fix this:
In your kernel.php file, you can move the middleware \Illuminate\View\Middleware\ShareErrorsFromSession::class back to the protected $middleware property.
You can wrap all your web routes with a route group and apply the web middleware to them.
Route::group(['middleware' => 'web'], function() {
// Place all your web routes here...
});
Solved
You may change any one of the following:
1. put your working route (app/http/routes.php) on
Route::group(['middleware' => ['web']], function () {
// Here like
Route::get('/', 'TodoController#index');
Route::post('/', 'TodoController#store');
});
Screenshot -
2. Move your protected $middlewareGroups web (app/Http/Kernel.php) on protected $middleware = []
Screenshot -
This is solution:
Change the defination of your Route groups with a middleware, from :
Route::group(['middleware' => 'web'], function () {
to
Route::group(['middlewareGroups' => 'web'], function () {
Source: https://github.com/laravel/framework/issues/13000
simply, you have to move :
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
from protected $middlewareGroups to protected $middleware
Just remove , 'middleware' => 'web' from Route::group(array('prefix' => 'user', 'middleware' => 'web'), function() in routes.php page OR
Move
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
From protected $middlewareGroups to protected $middleware in kernel.php page
As the Laravel Documentation says:
Note: If your copy of Laravel has a RouteServiceProvider that already
includes the default routes file within the web middleware group, you
do not need to manually add the group to your routes.php file.
So removing from routes.php file would be the correct way.
Posting this as it might be useful for others,
As Smartrahat mentioned in 1st solution, in your Kernel.php file(app/Http/Kernel.php) move \Illuminate\View\Middleware\ShareErrorsFromSession::class
from $middlewareGroups to protected $middleware property, but the same will start throwing the error "Session store not set on request",
to resolve this move
\Illuminate\Session\Middleware\StartSession::class, to $middleware property as well.
As of 5.2, routes.php is by default already called in the context of a ['middleware'=>'web'] by RouteServiceProvider. But in routes.php default generation of auth routes, the Route::group call is still happening by default - so if you delete that Route::group declaration from routes.php the application then correctly shows errors.
A couple of observations regarding this issue. First off there a related bug in github regarding this issue
PFA
https://github.com/laravel/framework/issues/12022
If you look at the last comment which Graham wrote, I think that is the facing I was facing.
For me even though there was a error in form post data, I was getting the below equality
boolval(count($errors) === 0) === true
In my case I added log statements in the
\Illuminate\Session\Middleware\StartSession::class
the above middleware class ran twice for a given request, I am not sure why it ran twice, but I think because of this the $errors variable is getting reset.
I was using this configuration (which I think came default with Laravel#5.2.43)
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
I changed the configuration which worked for me and the $errors variable's count is not zero (also the above middleware ran only once per request)
protected $middleware = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
Note:
All my routes are in the web middleware group before and after the Kernel.php configuration change, I didnot move my routes at all from the web middleware group.
Change #foreach($errors->any() as $error) to #foreach($errors->all() as $error)
in this case laravel 5.2 you can refer may example code and edit your kernal.php file. move this \Illuminate\View\Middleware\ShareErrorsFromSession::class, form middlewareGroups to middleware and add \Illuminate\Session\Middleware\StartSession::class, to middleware
then its work correctly.
Having both Web and API requirements in our application, we did not want to move the middleware around; perhaps that would have worked, however:
We had the very peculiar situation that the flash[] and $errors session data was transmitted correctly between the standard laravel resource methods, store() and edit(), but in some cases the data did not get back across nearly identical methods, storeSale() and editSale().
We found that in our development and deployment environments, the 'file' and 'database' session drivers worked in all cases, but the 'cookie' driver did not.
Switching to the database driver in all instances solved the problem.

Categories