behnampmdg3's avatar

A Question About "Authorizing Form Requests"

Hello;

Can someone please translate these 2 lines in the authorize() function.

Also, explain how does the code know the relation between user and comment.

public function authorize()
{
    $comment = Comment::find($this->route('comment'));
    return $comment && $this->user()->can('update', $comment);
}

The doc isn't explaining the relation and what $this->route does.

https://laravel.com/docs/5.7/validation#authorizing-form-requests

Thanks

0 likes
3 replies
crnkovic's avatar

Okay. So, FormRequest class inherits the Laravel's Illuminate\Http\Request class, which is like a god Request class. It contains everything, from the authenticated user ($this->user()), to URI, to the route parameters ($this->route('param')).

Your route is probably defined like this, or something similar:

Route::post('comments/{comment}', 'SomeController@someMethod);`.

$this->route('comment') will return whatever is defined in {comment}, like /comments/10, $this->route('comment') will return 10. :)

$this->user() returns user making the request. It's similar to Auth::user().

What this method does, it checks to see if the user is authorized to perform the request. They do it by finding the comment in question and checking if the comment exists and if the user can (note: Laravel's authorization functionality) update that comment.

$comment = Comment::find($this->route('comment')); // this line finds the comment from the route parameter

// if the $comment is not found (null), this will return false
// otherwise, check if currently authenticated user can update a comment (runs a Gate check)
return $comment && $this->user()->can('update', $comment);
1 like
behnampmdg3's avatar

Hi;

First thing, you mention $this->route('user') prints the id. But $this->route('user') shows a json

{"id":3064,"username":"Behnam 3456","email":"[email protected]","email_verified_at":null,"created_at":"2018-10-15 12:52:11","updated_at":"2018-10-15 12:52:11","owner_id":1}

(Sorry I changed "comment" to "user"!)

Also in UserController

echo $this->user();

prints

Method App\Http\Controllers\UserController::user does not exist.
shez1983's avatar

you either do \Auth::user() or $request->user() provided the controller func has Request in its func params..

Please or to participate in this conversation.