Lovelock
Lovelock

Reputation: 8085

Passing a parameter into Laravel middleware

Building a blog platform and my goal is to stop a user from being able to directly access any pages that allow them to post under a different user.

For example, they have created a blog 'Blog 1'

If a different user goes to add a new post to that blog:

/blog/newupdate/1

Then I want to block that.

I have methods set up already for my user as I check it in the views, but need a way to block this access.

I have a middleware set up in a group:

Route::group(['middleware' => 'auth','OwnsProject'], function () {
    Route::get('/project/newupdate/{id}',[
        'as' => 'project/newupdate',
        'uses' => 'ProjectController@createUpdate'
    ]);
});

In my middle ware I want to do:

public function handle($request, Closure $next)
{
    if (!Auth::user()->ownsProject($id)) {
        // nada
    }
    return $next($request);
}

But nothing seems to be coming through in the request?

Upvotes: 1

Views: 128

Answers (3)

Vikas
Vikas

Reputation: 993

Your OwnsProject middleware is not being applied to your route. If you are using 2 or more middleware, you must pass them in an array:

Route::group([ 'middleware' => ['auth','OwnsProject'] ], function () {
    Route::get('/project/newupdate/{id}',[
        'as' => 'project/newupdate',
        'uses' => 'ProjectController@createUpdate'
    ]);
});

As mentioned in Vishal's answer, this will return you the value of 'id' in your middleware.

$id = $request->route()->getParameter('id');

So you should do something like this in your middleware

public function handle($request, Closure $next)
{
    $id = $request->route()->getParameter('id');

    if ( !( \Auth::user()->ownsProject($id) ) ) {
        return redirect('/'); // Or anything else you want
    }
    return $next($request);
}

Upvotes: 0

Ozan Kurt
Ozan Kurt

Reputation: 3866

Just use the route method on your request object.

$id = $request->route('id');

Upvotes: 0

Vishal Sharma
Vishal Sharma

Reputation: 2610

you can access the id parameter using your request object as

$id = $request->route()->getParameter('id');

followed by your rest of the code:

public function handle($request, Closure $next)
{
    $id = $request->route()->getParameter('id');

    if (!Auth::user()->ownsProject($id)) {
        // nada
    }
    return $next($request);
}

Upvotes: 1

Related Questions