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');
}
});
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');
}
you can do this directly in your blade code by this way
@if (!Auth::guest())
do this
@else
do that
@endif
if you want authentication middleware for single route then
// Single route
Route::get("/awesome/sauce", "AwesomeController@sauce", ['middleware' => 'auth']);
if you want auth middlesware on multiples routes then use :
// Route group
Route::group(['middleware' => 'auth'], function() {
// lots of routes that require auth middleware
});
U can use midlleware in colntroller
All actions in controller require to be logged in
public function __construct()
{
$this->middleware('auth');
}
Or u can check it in action
public function create()
{
if (Auth::user()) { // Check is user logged in
$example= "example";
return View('novosti.create')->with('example', $example);
} else {
return "U cant access here!";
}
}
also u can use it on route
Route::get('example/index', ['middleware' => 'auth', 'uses' => 'example@index']);
use
Auth::check()
more here https://laravel.com/docs/5.2/authentication#authenticating-users in Determining If The Current User Is Authenticated