1
votes

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?

1
There is something not adding up here. Why are you using $this->reason->getKey() when Reason is being passed in via the function. Can't that just be $reason->getKey()? And why would $this->reason return to you the value of the reason column? If you are using dependency injection, that should return to you the instance of Reason and work fine. - user1669496
@user3158900 I'm using the $this->entityName->getKey() approach in plenty of other places and it works fine. In this case $this->reason returns the reason column value, rather than the entity like it normally would. - Dallin
I think we need to see more code, it's not clear what $this->reason is doing, let's start with where you are trying to call that? - tam5
I have a FormRequest class set up for validation, I'm calling $this->reason inside the rules method of that class. - Dallin
It sounds like somehow, somewhere, someone is setting the properties of your FormRequest class 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 the id of Reason by using $this->id. Maybe it's not as good as getKey() because it is assuming your database structure but it sounds like your database structure is pretty static anyway. - user1669496

1 Answers

2
votes

I was able to get around this by doing:

$this->route('reason')->getKey()