13

I am coding some thing like 'school club manage system' and meet some problem on rights authorization of resource .

Suppose there are club , and club have manager , and i want to check if the user is a manager of club before he can manage it with a middleware.

Using laravel 5.2

My router looks like that :

Route::resource('club', 'ClubController');

The middleware I create looks like that :

  public function handle($request, Closure $next)
    {
        if (!Auth::check()){
            // ask user to login
        }

        $club = Club::findOrFail($request->input('club'));
        $user = Auth::user();

        if (!$club->managers->contains($user)){
            //tell user your are not manager .
        }

        return $next($request);
}

But I failed to get the id of club from requests .

How can I solve the problem ?

Thanks in advance .

4 Answers 4

27

if you are looking for the url parameters the best way of getting that from the resource routes in laravel 5.2 inside the middleware is below. Lets say you want to get id parameter form url club/edit/{id}

$request->route()->parameter('id');
Sign up to request clarification or add additional context in comments.

1 Comment

From inspecting the source you can pass the parameter name to the route method and it works the same way, $request->route('id')
11

A shorter syntax is:

$request->route('parameter_name');

Comments

1

Woops , I found the ans after checking dd($requests).

I can use $requests->club to get parameter .

Thanks everyone.

1 Comment

Also it would be fair to do an existence check before doing findOrFail whether request has the data using !empty($request->club) or by $request->has('club') to avoid an unnecessary database read.
0

I am on Laravel 5.5 and

dd($request->route()->parameter('id'));
dd($request->route('id'));

worked for me

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.