Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 check whether a user is logged in

Tags:

I am new to Laravel 5 and trying to understand its Auth process. I want to prevent user to reach some of my pages unless the user is not logged in. Trying to make it with Route:filter but it does not work. What i have done wrong ?

Route::filter('/pages/mainpage', function() {     if(!Auth::check())      {         return Redirect::action('PagesController@index');     } }); 
like image 923
Tartar Avatar asked May 08 '15 07:05

Tartar


People also ask

What does Auth :: check () do?

In other words, Auth::check() calls Auth::user() , gets the result from it, and then checks to see if the user exists. The main difference is that it checks if the user is null for you so that you get a boolean value. As you can see, it calls the user() method, checks if it's null, and then returns a boolean value.

What is Auth :: attempt in laravel?

The attempt method accepts an array of key / value pairs as its first argument. The password value will be hashed. The other values in the array will be used to find the user in your database table. So, in the example above, the user will be retrieved by the value of the email column.

How do I authenticate in laravel?

How do I enable authentication in Laravel? You need to Install the laravel/ui Composer bundle and run php artisan ui vue –auth in a new Laravel application. After migrating your database, open http://your-app.test/register or any other URL that's assigned to your application on your browser.


2 Answers

You should use the auth middleware. In your route just add it like this:

Route::get('pages/mainpage', ['middleware' => 'auth', 'uses' => 'FooController@index']); 

Or in your controllers constructor:

public function __construct(){     $this->middleware('auth'); } 
like image 109
lukasgeiter Avatar answered Oct 21 '22 13:10

lukasgeiter


use

Auth::check() 

more here https://laravel.com/docs/5.2/authentication#authenticating-users in Determining If The Current User Is Authenticated

like image 30
Ivan Avatar answered Oct 21 '22 14:10

Ivan