Framework: In L 7.12 a belongsToMany relation returns null instead of an empty collection if there are no results

Created on 20 May 2020  Â·  9Comments  Â·  Source: laravel/framework

  • Laravel Version: #7.12.0
  • PHP Version: #7.4.1
  • Database Driver & Version: mysql Ver 15.1 Distrib 10.4.10-MariaDB, for Linux (x86_64) using readline 5.1

Description:

I get an error in this version of Laravel, but the code was working in #7.11.0.

In Laravel #7.12.0. a belongsToMany relation returns null instead of an empty collection if there are no results.

Steps To Reproduce:

Make a code like:

$paycheck = Paycheck::find(1);
$paychecks->load(['invoice', 'invoices']);

dd($paycheck->invoices);

Laravel 7.11:

App\Collections\InvoiceCollection {#2375 â–¼
  #items: []
}

Laravel 7.12
null

needs more info

Most helpful comment

@martijnderidder, maybe you are (also) hitting #32972? Do you have a cast on your (Eloquent magic) invoices attribute?

@riddla yes haha that is my colleague

All 9 comments

I think this was caused by https://github.com/laravel/framework/commit/353442d80722e8862c3f140b7e34c27578e89f7d. @martijnderidder can you undo the change locally to confirm?

I get an empty collection:
image

Share your model and relationship definitions.

He Taylor, i am not sure what information you need. I removed the company code, but its something like this:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Paycheck extends Model
{
    public function invoice()
    {
        return $this->belongsTo(Invoice::class);
    }

    public function invoices()
    {
        return $this->belongsToMany(Invoice::class);
    }
}

I think this was caused by 353442d. @martijnderidder can you undo the change locally to confirm?

I did undo the change and keep getting the same result. So i guess this is not the problem.

I still can't recreate this. At this point your best bet is probably to PR a failing test to the framework that can prove this is a bug.

@martijnderidder, maybe you are (also) hitting https://github.com/laravel/framework/issues/32972? Do you have a cast on your (Eloquent magic) invoices attribute?

@martijnderidder, maybe you are (also) hitting #32972? Do you have a cast on your (Eloquent magic) invoices attribute?

@riddla yes haha that is my colleague

@martijnderidder you may have a field in the table with the same name as the relationship name, which is just null. I had a similar error and deleted this field from the table. If the attributes have the same name, it will replace the relation when calling
$user->roles. And here you can use $user->getRelation('role'), but it is better not to make the same names.

Was this page helpful?
0 / 5 - 0 ratings