rranj
rranj

Reputation: 288

Auth::guest() returns true for both logged in and logged out users

I am new to laravel and so I was trying to create a small project for learning purpose. I have used the inbuilt Auth for login and register. These automatically generated pages work so well, now In this I created a route to resource posts by using controller called postcontroller.

Now in the postcontroller I check if the user is authorized to return a view: posts else to login page. So to check it I do following

if (!Auth::guest())

return view('posts');

else

return "......";

Now here the Auth::guest() returns true for both logged in and logged out users.

Upvotes: 3

Views: 22791

Answers (4)

asghar
asghar

Reputation: 447

you can use

if(!Auth::user())

//user not login

else

//user logined

Upvotes: 0

Izac Mac
Izac Mac

Reputation: 502

But You MUST add this line of code for the middleware to know in postcontroller that it needs for check for logged in users.Add this is PostController:

public function __construct()
{

    $this->middleware('auth', ['except' => ['index', 'show']]);
}

After this you need to make sure the routes are added onto the route list. This is done by adding the given line in Routes/web.php

Route::resource('user','PostController');

recheck if its added by typing the below command in terminal:

php artisan route:list

Once the route is added, the controllers know they can talk to each other, you are all set.

Note: Except means user can access ONLY index and show routes if user is logged in . Look at laravel documentation here for more details. Hope this helps.

Upvotes: 0

Clayton.
Clayton.

Reputation: 1

You need to make sure you use the 'web' middleware. By default, the home page does not use this but the /home route does, which is why the blade templates work under /home.

Add the 'web' middleware and dd(Auth::user()) and you'll see better results.

Upvotes: 0

Rafael Ferreira
Rafael Ferreira

Reputation: 41

Are you sure that you are logged in?

try to dump your Auth::user() data with

dd(Auth::user());

And by the way, if you are returning in the if statement you do not need to use else.

Upvotes: 2

Related Questions