Using Laravel prepareForValidation to add a new property

Issue

I am using Laravel’s form request class to try and add a new property to my $request via the prepareForValidation method.

Basically it takes the ‘id’ from the URL then uses it to return a relationship on a model.

It works sometimes, but other times i keep getting a Attempt to read property "transaction" on null error.

The way I am trying to do this is as follows;

protected function prepareForValidation()
{
    $this->merge([
        'transaction_slug' => History::find($this->route('id'))->transaction->transaction_slug,
    ]);
}

Solution

Make sure, you added transaction_slug and its validation rules into the rules array.

public function rules(): array
{
    return [
        'transaction_slug' => 'present',
        // other rules.
    ];
}

If you did it already, make sure your query returns not null. If you need null safe, add ‘?’ the way I did.

'transaction_slug' => History::find($this->route('id'))?->transaction->transaction_slug,

If you need a default value in the case of returning null

$history = ;

$this->merge([
    'transaction_slug' => (History::find($this->route('id')) ?? History::first())->transaction->transaction_slug,
]);

Answered By – Bulent

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published