简体   繁体   中英

How to Check whether the user logged in and Redirect Accordingly

Here is my Route :

Route::get('/', 'HomeController@home');
Route::post('login', 'LoginController@Login');
Route::get('vehicle', 'VehicleController@VehicleLayout');

So far all pages can be accessed by any users.

And I started using auth::user So

    if (Auth::attempt($LoginData))
    {
        return Redirect::intended('dashboard');
    }
    else
    {
        return Redirect::to('')->with('Message', 'UserName or Password Invalid');
    }

I am checking in the Login screen.

But from my above code. The page vehicle can be accessed from any where. And there i am getting the logged in user's details by {{ Auth::user()->FirstName}}

And when i try to access the vehicle page, If the user didn't logged in it simply throws the error

Trying to get property of non-object (View: C:\xampp\htdocs\mti\app\views\layouts\dashboardlayout.blade.php) (View: C:\xampp\htdocs\mti\app\views\layouts\dashboardlayout.blade.php)

Is there any way to check whether the user has logged in and Redirect the user to login page with errors in laravel way.

<?php
if (Auth::guest())
{
    return Redirect::to('logout')->with('Message', 'You Must Logged In to Access this page.');
}
?>

Is the above given a good process or is there any laravel way to do this.

You can and should use filters for this. There's even a built in auth filter (you can find it inside app/filters.php )

It works very well in combination with route groups. Here's an example:

Route::group(array('before' => 'auth'), function(){
    Route::get('vehicle', 'VehicleController@VehicleLayout');
    Route::get('foo', 'FooController@BarAction');
});

In laravel it's simple to do what you are asking.

There is a function to check values from login form, and then check if the user exists in database.

if (Auth::attempt(array( 'email' => $email, 'password' => $password ) ) )
{

return Redirect::to( 'your route' );     // route for loged users

}else
{

return Redirect::to('/home')->withMessage('Wrong username/pass')

}

On the home page you can display error message like this {{ If(Session::has('message') {{ $message}} }}

If you have that user in database, the function will redirect you to page where loged user go, and then you can type Auth::user()->username, and you will be able to acces any data of that user.

**To check if the user is loged, just type

if(Auth::check){
then do something
}else{
do something else
}**

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM