1
votes

I am trying to make user show their report only. Not authenticated user showing other users report. But, admin could show all users report. I have this route:

Route::get('/showReport/{id}', 'CeciController@showReport');

I want this route to be accessed by only authenticated user which has that report id and the admins. If i put it in auth middleware group, authenticated user can acess others users report.showReport/4, showReport/5, showReport/6. And if i put it under admin middleware group. Even the authenticated user of that id can't acess it. How can this be acheived?

View:

Report for the month <b> {{$report->month}}: </b> <a href="{{url('/showReport', [$report->id])}}">Show Report Details</a>

Here is the controller:

public function showReport($id)
    {
        $report=Report::where('id',$id)->first();
        if($report)
        {
            return view('show_report')->with('report',$report);
        }      
    }
1

1 Answers

1
votes

You can create a new middleware and check if the Authenticated user's id matches the given id parameter:

public function handle($request, Closure $next)
{
    # Allow only if the user is admin or id matches
    $user = Auth::user();
    if ($this->isAdmin($user) or ($request->input('id') === $user->id)) {
        return $next($request);
    }

    return response('Unauthorized.', 401);
}