Matt Komarnicki
Matt Komarnicki

Reputation: 5422

How to pass (access) ID inside rules method in Laravel 5?

I'm populating my form with user's data using form model binding.

{!! Form::model($user, ['route' => ['user_update', $user->id]]) !!}

Works perfectly. When I hit "Submit" I enter my UpdateUserRequest where I validate my input against some rules. In this case I want to keep unique e-mail address but of course we need to "skip uniqueness" for "this" row.

I have a rule

'email' => 'required|unique:users,email,' . 123456,

and it works good as well when I will temporarily hardcode this ID (primary key from users table).

How to access this ID inside rules method? (Especially when I pass $user_id from controller).

  1. Yes, Auth::user()->id works but obviously just for me. I deal also with profiles of other users.
  2. I could pass this user's ID as input hidden and the access this from request / input but I don't find this as a good solution, am I right?
  3. The same with url segment. I could grab this from url probably but maybe there is better way?

I'm inside rules() method and I'm dd() bunch of things but nothing works so far as I expect.

Thanks for any hints! :)

Upvotes: 0

Views: 1883

Answers (2)

Matt Komarnicki
Matt Komarnicki

Reputation: 5422

OK, the solution was very very easy.

$this->user->id

Full rule below:

'email' => 'required|unique:users,email,' . $this->user->id,

Works like a charm!

Upvotes: 2

lukasgeiter
lukasgeiter

Reputation: 152900

You can retrieve route parameters by their name with route()->parameter():

$userId = $this->route()->parameter('userId'); // or whatever the name of the parameter is

Or a shortcut:

$userId = $this->route('userId');

Upvotes: 3

Related Questions