3

In my Laravel application, I have this model:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Division extends Model
{

    protected $fillable = [
               'name','company_id', 'location_id'
               ];

    protected $casts = [
                'name' => 'string',
                'company_id' => 'integer',
                'location_id' => 'integer'
                ];

    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    public function location()
    {
        return $this->belongsTo(Location::class);
    }

}

$division->company returns a collection

$division->location returns an array

Why this two relations has different results? (Sorry for bad formating....)

3
  • Can you show us the code where you call location relationship? Commented Feb 9, 2018 at 15:13
  • Both must return an object and not a collection or an array. Commented Feb 9, 2018 at 15:14
  • @foreach($companyDivisions as $division) <tr> <td>{{$division->name}}</td> <td>{{$division->location->name}}</td> </tr> @endforeach Commented Feb 9, 2018 at 15:16

1 Answer 1

2

As you've just shown in the comments (and then edited), you're using it with get(). That's why you're getting a collection and not an object.

$division->company returns an object. Then you're running another query with $division->company->anotherRelationship()->get() which returns a collection of related objects.

Sign up to request clarification or add additional context in comments.

6 Comments

Sorry, still not understand. In my opinion, I'm doing the same in both cases. $division->company->name shows the name of the company $division->location['name'] shows the name of the location $division->location->name give an error (Trying to get property of non-object)
@Peter before that you've shown something like $division->company->anotherRelationship()->get() in the comment. Trying to get property of non-object is a whole different error and you get it because the division is not associated with any company, so you get null instead of a Company object.
But why $division->location['name'] shows the name and $division->location->name gives an error?
@Peter because it's null
Thanks for your help. I didn't change anything but now it's working. It's really strange for me...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.