Routes accessible only to users logged in to Laravel?

Asked

Viewed 2,910 times

3

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

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

  • Read: https://answall.com/questions/119043/comoreredirecionar-o-usu%C3%A1rio-autenticado-para-uma-p%C3%A1gina-espec%C3%Adfica

  • Read: https://answall.com/questions/154386/routes-laravel-5-3/154413#154413

3 answers

4


For this, you will use Middleware.

Middleware

Middleware provides a mechanism for filtering HTTP requests on its application. For example, Laravel includes a middleware that checks if the user of your application is authenticated. If the user is not authenticated, middleware will redirect the user to the login tab. However, if the user is authenticated, middleware will allow the request to proceed further in its application.

Auth Middleware

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

Specific Route

Assigning the middleware route via fluent method.

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

Route Group

Assigning 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 directly 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');
    }
}

1

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

An example from 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 route with a Middleware:

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

1

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

Route::group(['middleware' => ['auth']], function () {
     Route::get('sua_url', function());
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.