I'm using route model binding in a FormRequest class with unique validation rules
class ReasonUpdateRequest extends FormRequest
{
public function rules()
{
return [
'reason' => 'string|max:255|unique:reasons,reason,' . $this->reason->getKey(),
];
}
}
And here's the controller method
public function anyReasonUpdate(ReasonUpdateRequest $request, Reason $reason)
{
//
}
I've always been able to access the model that is being bound by doing $this->entityName.
The problem is that I can't do $this->reason->getKey() to access the id of the reason entity because Reason has a field named reason. Now instead of $this->reason pointing to the model, it points to the value in that field. I know that a fix could be to rename the field but I'm not in a position to easily do that.
I can get it to work by doing $reasonId = $this->segment(4); but this couples it to the format of the url.
How can I access the Reason entity from within my form request object in a more generic way?
$this->reason->getKey()whenReasonis being passed in via the function. Can't that just be$reason->getKey()? And why would$this->reasonreturn to you the value of thereasoncolumn? If you are using dependency injection, that should return to you the instance ofReasonand work fine. - user1669496$this->entityName->getKey()approach in plenty of other places and it works fine. In this case$this->reasonreturns the reason column value, rather than the entity like it normally would. - Dallin$this->reasoninside therulesmethod of that class. - DallinFormRequestclass to the attributes of the model. I can't begin to guess how they are doing that exactly but if that's the case, you should be able to grab theidofReasonby using$this->id. Maybe it's not as good asgetKey()because it is assuming your database structure but it sounds like your database structure is pretty static anyway. - user1669496