2

I use php artisan make:auth function in Laravel 5.2.

I want to redirect guest to login page if guest clicks link that only for user not guest.

And I want to redirect users to back page after login.

How can I do this? Please show some examples with file name in detail.

///////edit

Route

// Routes for logged in users
Route::group(['middleware' => 'auth'], function() {
//write
Route::get('board/create', ['as' => 'board.create', 'uses' =>'BoardController@create']);
});

Controller

public function create() {

    return view('board.create');

}

Kernel.php

jungmyung
  • 319
  • 3
  • 13
  • Take a look at this answer here: http://stackoverflow.com/a/15393229/4199784 – S.I. Oct 13 '16 at 06:46
  • 3
    Possible duplicate of [Laravel redirect back to original destination after login](http://stackoverflow.com/questions/15389833/laravel-redirect-back-to-original-destination-after-login) – Danh Oct 13 '16 at 07:06

1 Answers1

2

This is achieved using Middleware. By default the App\Http\Middleware\RedirectIfAuthenticated and the \Illuminate\Auth\Middleware\Authenticate middleware are loaded. (Check your app/Http/Kernel.php file to check which middleware are loaded.

So with route groups :

// Routes for anyone
Route::get('guest-or-user', 'SomeController@action');

// Routes for guests only
Route::group(['middleware' => 'guest'], function() {
    Route::get('user-not-logged-in', 'SomeController@guestAction');
});

// Routes for logged in users
Route::group(['middleware' => 'auth'], function() {
    Route::get('user-logged-in', 'SomeController@userAction');
    // ... other routes
});

You can also do this in your controller:

// SomeController.php
public function __construct()
{
    $this->middleware('guest', ['only' => 'guestAction']);
    $this->middleware('auth', ['only' => 'userAction']);
}

public function action()
{
    // ...
}

public function guestAction()
{
    // ...
}


public function userAction()
{
    // ...
}

Read the doc: Protecting Routes

SimonDepelchin
  • 2,013
  • 22
  • 18