How to check route parameters in Laravel and only accept specific parameters?

1

I would like to know how to create a function that validates the parameter received from a route in Laravel , for example, has a route:

Route::get('fotos/{user_id}');

where users can only access where user_id is equal to the id of the logged in user.

In a quick search I found that laravel has Regular Expression Constraints that works

Route::get('user/{name}', function ($name) {
    //
})->where('name', '[A-Za-z]+');'

and Route Service Provider , I would like to know how I can create validation functions and how best to do something like this.

    
asked by anonymous 31.03.2017 / 15:05

1 answer

3

This is by no means the best solution in this case.

For this you can put the check in the controller, or in a simple way in the route as you mention in the question:

Route::get('/fotos/{user_id}', function() {
    if(Auth::user()->id != request()->user_id) {
        // não é... redirecionar sujeito
    }
    // é o utilizador login, continuar lógica, buscar as fotos do utilizador com este id
});

But attention :

I strongly advise you to use middleware for this, and laravel already has one by default:

  

/app/Http/Middleware/RedirectIfAuthenticated.php

That is, assuming that everything is fine with your authentication system, and if only the login user can access this route ("... users where user_id is equal to the id of the logged in user . "), you can / should:

Route::get('/fotos/user', function() {
    // se isto for executado é porque o utilizador está login
    $id_user = Auth::user()->id;
    // continuar lógica, buscar as fotos do utilizador com este id
})->middleware('auth'); // auth é o alias para o middleware descrito em cima, RedirectIfAuthenticated

DOCS

I noticed comments in the question (these details should be in the question itself), that you want to make a set of routes have the same processing, auth in this case, then you can group them (very well said by @ Virgilio Novic) in the same middleware, in this case all the routes of the group will be processed by the middleware auth :

Route::group(['middleware' => ['auth']], function() {

    Route::get('/fotos/user', function() {
        // se isto for executado é porque o utilizador está login
        $id_user = Auth::user()->id;
        // continuar lógica, buscar as fotos do utilizador com este id
    });

    Route::get('/perfil/user', function() {
        // se isto for executado é porque o utilizador está login
    });

});

DOCS

    
31.03.2017 / 15:22