laravel / framework

The Laravel Framework.
https://laravel.com
MIT License
32.54k stars 11.02k forks source link

[8.x] SerializesModels removes pivot from model used in Mailable #36855

Closed PhiloNL closed 3 years ago

PhiloNL commented 3 years ago

Description:

The pivot value is no longer available in my Mailable object. I've added a example repository below with all the code for easy verification.

class QuoteReceived extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;

    public $fields;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct(public Quote $quote)
    {
        $this->fields = $this->quote->fields()->get();

        // This returns 'foobar' which is correct
        // dd($this->fields[0]->pivot->value);
    }

So the dd returns the correct pivot value. Now the strange thing is, the pivot is lost when trying to access it in the blade file:

{{-- PHP Warning:  Attempt to read property "value" on null --}}
@foreach($fields as $field)
    <div>{{ $field->id }}: {{ $field->pivot->value }}</div>
@endforeach

{{-- For some reason this does work: --}}
@foreach($quote->fields as $field)
    <div>{{ $field->id }}: {{ $field->pivot->value }}</div>
@endforeach

Removing the SerializesModels trait resolves the problem. So I'm not sure if this intended behavior or a bug.

Steps To Reproduce:

Example code to reproduce: https://github.com/PhiloNL/laravel-issue

Run the migrations and dispatch the mailble via artisan tinker: Mail::to('hello@world.com')->send(new App\Mail\QuoteReceived(Quote::first()));

The email output should be:

1:
1: foobar
driesvints commented 3 years ago

Don't perform database queries in your job constructs.