How can i use Auth::user() in App\Exceptions\Handler class in Laravel 5.7? - laravel

I cant check if user is logged in. I need to load different error pages according to Request::segment() and Auth::check().
At that point Auth::check() is FALSE and Auth::user() is NULL.

Move \Illuminate\Session\Middleware\StartSession::class to the global $middleware array in App/Http/Kernel.php.

Related

Auth - get model

After using the Illuminate\Auth\Authenticatable trait on a model, I can now do Auth::id() in places in my app (when the current auth-ed thing is that particular model).
Is there a way to get the class / type of the auth-ed model?
Perhaps something like Auth::model() which might return the model's class name (such as App\Models\User or App\Models\MyCustomAuthCapabaleModel)?
Auth::user(); returns the model of the logged in user.
If you ever wish to change the User model, you can change it in config/auth.php at the key providers.users.model
Auth::user(); returns all the information about the authenticated user

auth()->user() returns unexpected user and different user

Why does auth()->user() returns different logged in user?
Tried debugging it..
dd(auth()->user())
I'm using AuthenticatesUsers trait in my LoginController
use
dd(Auth::user()); and if u want any particular field data
use
dd(Auth::user()->field_name);

Use multiple guard on one route in laravel

How i can use multiple guard on one route in laravel?
I have two guard: admin-api, user-api and i want to check if token for user is valid can be accessible, and if token not valid in users table, check token in admins table.
I use the following code but just second middleware Applied.
Route::middleware('auth:api')
->middleware('auth:api-admin')
->post('/user' , 'UserController#user');
It's been a while this question asked, but the other way to check multiple guards within one route without adding a custom middleware is pass several guards to auth middleware:
Route::middleware(['auth:api,api-admin'])->post('/user', 'UserController#user');
You can add an array of middlewares to your routes
Route::middleware(['auth:api', 'auth:api-admin'])->post('/user', 'UserController#user');

Laravel middleware is "bypassed" when i submit the invalid token, but when it is a valid token, the middleware is executed

all my fellow friends, i have a question.
Route::group([
'middleware' => ['ensure.role:store', 'auth:api']
]
For simplification,
i have two roles : ADMIN and STORE
I have created a middleware that will validate user role, and if the user role is correct, then will allow the user to access the route.
It works fine.
I tried using ADMIN Jwt Token to access STORE routes, and rightfully i am kicked out, and vice versa.
But now, if i modify the token, lets say i add a string to any part of the token, and try to access any route, actually i am allowed to.
I tried var_dump and print something on the related middleware, and here are my observation.
1. If the token is VALID as one of the user role, then
the var_dump is executed, (means the middleware is executed)
2. if the token is INVALID as in i add / modify the original
token, then the var_dump is not executed, and so are the
others route middleware.
I am wondering what causes this behavior, and what could be the fix for this issue, as i need to throw 401 unauthenticated in any token invalid case.
Thank you
I figured it out.
After series of testing and reading, i found out that after laravel 5.3 and above, constructor is called before middleware. And because in my constructor i am using an user object before i am authenticated by the middleware, i encountered constructor error, because user is null.
Of course it is a bad practice to use user object in the construct, however due to the convenience of usage, i still decided to use it.
It sounds complex to use closure based middleware as alternative solution
So i use a workaround to do it.
I create a helper function that return me true if there is an user object or return abort(401); if there is no user object, then add this one line to all the constructors.
$this->checkAccess = EnsureRoleUtil::check('admin');
After that, i just do my next constructor as normally
public function __construct() {
$this->checkAccess = EnsureRoleUtil::check('admin');
$this->user = Auth::user();
$this->categoryM = new CategoryManager($this->user);
}
However, to be noted, it is not a good practice, it is just a hack / workaround.

Undefined variable: errors in Laravel

When I want to register a user in my laravel project, the page always says
Undefined variable: errors (View: /var/www/resources/views/auth/register.blade.php)"
According to the Laravel documentation, $errors should always automatically be set:
So, it is important to note that an $errors variable will always be available in all of your views on every request, allowing you to conveniently assume the $errors variable is always defined and can be safely used.
I have this on on every view when I use:
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
or any other way when I want to use the $errors variable.
Why is this? I never had this problem before.
Can someone help me please?
You should make sure that in app/Http/Kernel.php in middlewareGroups property for web you have:
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
in this array. Compare this with https://github.com/laravel/laravel/blob/master/app/Http/Kernel.php
EDIT
It seems you need to add 'middleware' => 'web' for route you are using or put \Illuminate\View\Middleware\ShareErrorsFromSession::class, into $middleware property array
or
Inside of the routes.php file try to create your routes within the following block
Route::group(['middleware' => ['web']], function () {
//routes here
});
UPDATE FOR NEWER VERSIONS OF LARAVEL APPLICATION
Be aware that you might run into problems also in case you use web middleware twice. There was a change in Laravel application 5.2.27 (don't confuse it with Laravel framework you use at the moment - you might use Laravel framework for example 5.2.31 but have Laravel application in version 5.2.24) in which web middleware is applied automatically for all routes. So in case of problems, you should open your app/Providers/RouteServiceProvider.php file and verify its content.
You can compare it also here :
RouteServiceProvider for Laravel application 5.2.24
RouteServiceProvider for Laravel application 5.2.27
In case you have newer version (that applies web middleware automatically), you shouldn't use web middleware in routes.php anymore or you should modify your RouteServiceProvider method to not apply web group middleware. Otherwise if web middleware group is automatically applied in this provider and you use it also in routes.php you might get very unexpected results.
I had this very same issue with Laravel 5.2.x.
Inside of the routes.php file try yo create your routes within the
Route::group(['middleware' => ['web']], function () {
//routes here
}
statement.
Also to be aware of: If you write tests and your view has $errors variable make sure you don't use WithoutMiddleware trait.
I had similar problem and solved this one by adding routes into middleware property array as well,
BUT
it worked only after calling php artisan route:cache (clearing route cache) subsequently.
I hope some of you would find this useful.
I was seeing this error too and later realised I had used the WithoutMiddleware trait as a means to bypass authentication for this particular test, but it ended up removing the validation error binding too. So I had to stop using the trait to keep the views working.
Go to App\Http\Kernel.php file. Move all the things of $middlewareGroups properties to $middleware.
Check for more details-
http://www.tisuchi.com/laravel-5-2-undefined-variable-error-validation/
count is not really realiable since it assumes the variable already exists. change the condition check to: #if($errors->has()) or just #if($errors)
Also if you are redirecting make sure to use this in your controller
return redirect()->back()->with('errors', $validator->messages());
EDIT: seen now that you are using L5.2
This may answer your question - you need to put your Routes in Route group.
Laravel 5.2 validation errors
protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Social\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Social\Http\Middleware\VerifyCsrfToken::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
],
'api' => [
'throttle:60,1',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
make your kernel look like this
Your problem will be fixed by using this method.
Route::group(['middleware' => ['web']], function () {
//routes should go here
});
If this doesn't help you, just run the following artisan command in addition to the above code:
php artisan key:generate
I solved in this way while using 5.2.*

Resources