205 words, 2 min read

If you want to have auto-complete in your IDEA and good static analysis of your route parameters in Laravel, you should be using the RouteParameter and CurrentUser annotations.

I always used to do something like this:

class UpdatePost extends FormRequest
{
public function authorize(): bool {
/** @var User $user */
$user = Auth::user(); // Current user
/** @var Post $post */
$post = $this->route('post'); // Post from the request
return $post->user_id === $user->id;
}
public function rules(): array {
/** @var Post $post */
$post = $this->route('post');
return [
'slug' => [
'required',
'string',
Rule::unique(Post::class, 'slug')->ignore($post->id);
// ...
];
}
}

The phpdoc strings were needed to get the proper type support, but I somehow don't like them.

When using the proper annotations, you can do this instead:

use Illuminate\Container\Attributes\CurrentUser;
use Illuminate\Container\Attributes\RouteParameter;
class UpdatePost extends FormRequest
{
public function authorize(
#[CurrentUser] User $user, // The current user
#[RouteParameter('post')] Post $post // The post from the route
): bool {
return $post->user_id === $user->id;
}
public function rules(
#[RouteParameter('post')] Post $post // The post from the route
): array {
return [
'slug' => [
'required',
'string',
Rule::unique(Post::class, 'slug')->ignore($post->id);
// ...
];
}
}

This has been added in Laravel 11.28.x with this pull request.