I was working with localization and had to add \Illuminate\Session\Middleware\StartSession::class, to my kernel.
My previous question about it here.
But now my $errors is always empty and the errors don't show up in view.
I also tried adding \Illuminate\View\Middleware\ShareErrorsFromSession::class, after StartSession to my kernel but the errors are still empty.
Controller :
public function postRegister(Request $request) {
$request_data = $request->all();
$request->validate([
'first-name' => 'required',
'last-name' => 'required',
]);
//other processing stuff
}
kernel
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\Localization::class,
];
/**
* 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',
'bindings',
],
];
/**
* 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,
];
}
I read errors like this {{ $errors->first('first-name') }}
What am I doing wrong?
I think you are adding StartSession and ShareErrorsFromSession into a wrong variable, they are not alone HTTP middlewares, but rather features of a certain group of middleware, for example.
Web is a middleware group which includes various smaller middleware's which enrich further usable features which evolve around Request, like using Cookie, Session, CsrfToken, etc.
Try removing StartSession and ShareErrorsFromSession from $middleware variable.
EDIT: Also show us your Localization.php code, thanks
I had the same problem and I solved it by adding StartSession class then Localization class in $middlewareGroups web array and not in $middleware
because if you put it in $middleware (executed every HTTP request) the old session will be removed then create a new session.
Related
Alright so I got this locale system with a middleware, the issue is that when I enter language "hu"it doesnt set it the first time, it usualy works only the 2nd time I do it...
web.php
Route::get('set_language/{locale}', function ($locale) {
Session::forget('my_locale');
session(['my_locale' => $locale]);
return Redirect::back();
});
Language.php inside HTTP/middleware
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Foundation\Application;
class Language {
public function __construct(Application $app, Request $request) {
$this->app = $app;
$this->request = $request;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$this->app->setLocale(session('my_locale', config('app.locale')));
return $next($request);
}
}
And of course I added it inside my Kernel.php on couple of spots that seemed correct
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\Language::class,
];
/**
* 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,
\App\Http\Middleware\Language::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
/**
* The priority-sorted list of middleware.
*
* This forces non-global middleware to always be in the given order.
*
* #var array
*/
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\Language::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];
}
EDIT:
I forgot to mention, but in the config/app.php I've set it this way
'locale' => 'rs',
'locales' => ['rs', 'hu'],
'fallback_locale' => 'rs',
'available_locale' => ['rs', 'hu'],
So now If I got to the localhost:8000/set_language/rs it works, but if I do localhost:8000/set_language/hu it works only after I do it twice.
I tried dumping the session key my_locale and it stays as "rs" until I do the set_language/hu twice
So how I do it?
Go to: localhost:8000/set_language/hu
Go again to: localhost:8000/set_language/hu
Now it works...
Why isnt it being set the first time around?
Just to add up, if you are testing this, try setting your locale to RS first and then try to set it to HU
I am building a laravel application where I have web and api routes.
I want to store sessions between my routes.
If i store as session without returning a view, it works fine.
But when i return a view my session no longer exists.
My web.php is as follows:
Route::get('/', 'ViewController#index');
Route::get('/check', 'ViewController#check');
My controller
public function index(Request $request)
{
$request->session()->put('test','123456');
$request->session()->save();
//echo $request->session()->get('test', 'default_value');
// return view('welcome'); //If I uncomment this the sessions are not working anymore.
}
public function check(Request $request)
{
echo $request->session()->get('test', 'default_value');
var_dump($request->session()->all());
//return view('welcome');
}
Maybe it has something to do that i also store sessions in my api routes in the api controllers. My api.php:
Route::group(['middleware' => ['web']], function () {
//board
Route::get('/board/create', 'BoardController#create');
Route::post('board/{id}/guess', 'BoardController#guessWord');
Route::get('/board/set', 'BoardController#set');
Route::get('/board/get', 'BoardController#get');
//user
Route::get('/user', 'UserController#get');
Route::post('/user/create', 'UserController#create');
});
kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
];
/**
* 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',
'bindings',
],
];
/**
* 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,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}
Thanks!
From the docs api routes does not use StartSession middleware because session is only available in web group of middlewares
So store session only in web routes
When I call:
Auth::loginUsingId($user->id, true);
print_r(Auth::user());
...It's ok. But when I have this function after that:
return redirect('/');
Now in mydomain.com I called print_r(Auth::user()); and it return null;
Here is my Kernel.php
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\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,
];
/**
* The application's route middleware.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'admin' => \App\Http\Middleware\AdminMiddlware::class
];
}
Laravel version: Laravel Framework version 5.1.46 (LTS)
Authentication works fine using 'middleware' => 'auth:api' on regular endpoints where the client sends the Authorization=Bearer <access_token>.
But now I'd like to handle plain image download requests, without Authorization header, having the access token in the query string like this: GET /picture/my_picture.png?access_token=1234.
I tried something like this in my middleware, but I can't seem to add headers to the Request:
if ($request->has('access_token')) {
// something like $request->header->set('Authorization', 'Bearer ' . $request->get('access_token'));
}
if ($this->auth->guard($guard)->guest()) {
// throw exception
}
Can this be done? Maybe intercept or override something/somewhere else?
I had similar issue
In your
App\Http\Kernal.php
register your middleware in
$middleware and
$routeMiddleware
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\App\Http\Middleware\AddHeaderAccessToken::class,
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* 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',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'addAccessToken' => \App\Http\Middleware\AddHeaderAccessToken::class,
'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,
'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,
'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class
];
}
Middleware
<?php
namespace App\Http\Middleware;
use Closure;
class AddHeaderAccessToken
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($request->has('access_token')) {
$request->headers->set('Authorization', 'Bearer ' . $request->get('access_token'));
}
return $next($request);
}
}
I understand in Laravel 5.3 they have deprecated Route Filters in favor of middleware. This is discussed here.
I am trying to do something similar but instead of defining a Route pattern I want to define a "filter" where I check the logged in user for a certain condition and redirect the user if this condition is not met. I want this filter to be globally applied to the app.
How can I do this? I only see documentation for the Route::pattern method but Route::filter does not exist.
You can use Laravel Middlewares like this:
To create a new middleware, use the make:middleware Artisan command:
php artisan make:middleware CheckUserAge
And your CheckUserAge.php class should look like this:
<?php
namespace App\Http\Middleware;
use Closure;
class CheckUserAge
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (auth()->user->age <= 20) {
return redirect('home');
}
return $next($request);
}
}
If you want a middleware to run during every HTTP request to your application, simply list the middleware class in the $middleware property of your app/Http/Kernel.php class.
// Within App\Http\Kernel Class...
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,
// insert your middleware here <--------------
'checkUserAge' => \App\Http\Middleware\CheckUserAge::class,
];
Out of the box, the web middleware group is automatically applied to your routes/web.php file by the RouteServiceProvider.
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,
\App\Http\Middleware\CheckUserAge::class, // <------- add here too
],
];
See more about Middlewares in Laravel
Hope this helps!