Routes accessible only to users logged in to Laravel?

2

Can anyone give me a hint on how to create routes that can be accessed only by users who are authenticated using Laravel ?

For example , routes that relate to sharing, editing, deleting, and viewing publications are accessible only to users who are logged in.

    
asked by anonymous 24.08.2017 / 23:41

3 answers

3

For this you will use Middlewares .

Middlewares

  

Middleware provides a mechanism for filtering HTTP requests in the   application. For example, Laravel includes middleware that   verifies that the user of your application is authenticated. If the user   is not authenticated, the middleware will redirect the user   to the login page. However, if the user is authenticated,   the middleware will allow the request to move forward in your application.

Auth Middleware

Laravel already comes with some middleware for you to use, and one of them is auth . You can apply this middleware in a number of ways.

Specific Route

Assigning the middleware to the route via the fluent method.

Route::get('admin/posts/create', function () {
    //
})->middleware('auth');

Routing Group

Assigning the middleware to a group of routes.

Route::middleware(['auth'])->group(function () {
    Route::get('admin/posts/create', function () {});
    Route::get('admin/user/profile', function () {});
});

Via Controller

You can assign direct to the controller as well.

class PostsController extends Controller
{
    public function __construct()
    {
        // Nesse caso o middleware auth será aplicado a todos os métodos
        $this->middleware('auth');

        // mas, você pode fazer uso dos métodos fluentes: only e except
        // ex.: $this->middleware('auth')->only(['create', 'store']);
        // ex.: $this->middleware('auth')->except('index');
    }
}
    
25.08.2017 / 17:36
1

Another option is to group the routes you want to protect, like this:

Route::group(['middleware' => ['auth']], function () {
     Route::get('sua_url', function());
}
    
25.08.2017 / 00:35
1

For this you can use Laravel's Middleware , which are basically functions performed before or after the route that can affect the execution of a controller / action.

An example of Middleware:

<?php

namespace App\Http\Middleware;

use Closure;

class BeforeMiddleware
{
    public function handle($request, Closure $next)
    {
        // Perform action

        return $next($request);
    }
}

An example of a Middleware route:

Route::get('admin/profile', function () {
    // Seu código
})->middleware('auth');
    
24.08.2017 / 23:45