RPeraltaJr
8/2/2019 - 3:42 PM

Auth Middleware to Specific Routes

Make pages/routes only accessible to logged in users (or vice-versa). (

There are two options in applying the auth middleware:

  1. Routes file (web.php)
  2. Controller's constructor

Documentation: https://laravel.com/docs/5.8/middleware

<?php 

// * Option 1 (Single)
Route::get('/admin', 'HomeController@index')->name('home')->middleware('auth'); // * Only viewable if IS authenticated
Route::get('/signup', 'HomeController@signup')->name('signup')->middleware('guest'); // * Only viewable if NOT authenticated (ex. Sign Up page)

// * Option 2 (Group)
Route::group(['middleware' => 'auth'], function() {
    Route::get('/projects', 'ProjectsController@index');
    Route::get('/projects/create', 'ProjectsController@create');
    Route::get('/projects/{project}', 'ProjectsController@show');
    Route::patch('/projects/{project}', 'ProjectsController@update');
    Route::post('/projects', 'ProjectsController@store');

    Route::post('/projects/{project}/tasks', 'ProjectTasksController@store');
    Route::patch('/projects/{project}/tasks/{task}', 'ProjectTasksController@update');
    
    Route::get('/home', 'HomeController@index')->name('home');
});
<?php

// ...
// ...

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth'); // * Option #2 
        
        // $this->middleware('auth')->only(['store', 'delete']); // Only to some routes
        // $this->middleware('auth')->except(['store', 'delete']); // Apply to everything EXCEPT...
        
    }
    
}