Home > Mobile >  Using Laravel prepareForValidation to add a new property
Using Laravel prepareForValidation to add a new property

Time:06-11

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,
    ]);
}

CodePudding user response:

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,
]);
  • Related