06.10.2016 Views

laravel-5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Validation 494<br />

Authorizing Form Requests<br />

The form request class also contains an authorize method. Within this method, you may check if<br />

the authenticated user actually has the authority to update a given resource. For example, if a user<br />

is attempting to update a blog post comment, do they actually own that comment? For example:<br />

1 /**<br />

2 * Determine if the user is authorized to make this request.<br />

3 *<br />

4 * @return bool<br />

5 */<br />

6 public function authorize()<br />

7 {<br />

8 $commentId = $this->route('comment');<br />

9<br />

10 return Comment::where('id', $commentId)<br />

11 ->where('user_id', Auth::id())->exists();<br />

12 }<br />

Note the call to the route method in the example above. This method grants you access to the URI<br />

parameters defined on the route being called, such as the {comment} parameter in the example below:<br />

1 Route::post('comment/{comment}');<br />

If the authorize method returns false, a HTTP response with a 403 status code will automatically<br />

be returned and your controller method will not execute.<br />

If you plan to have authorization logic in another part of your application, simply return true from<br />

the authorize method:<br />

1 /**<br />

2 * Determine if the user is authorized to make this request.<br />

3 *<br />

4 * @return bool<br />

5 */<br />

6 public function authorize()<br />

7 {<br />

8 return true;<br />

9 }

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!