Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cbcw's avatar
Level 2

@a4ashraf

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Kid extends Model
{
    use HasFactory;

    public function users()
    {
        //
        return $this->belongsToMany(User::class);
    }
}
automica's avatar

@cbcw nothing odd there. How about seeing your users/index.blade.php

a4ashraf's avatar

@cbcw

here is problem


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Kid extends Model
{
    use HasFactory;
    protected $guarded = [] // or even you use fillable 

    public function users()
    {
        
        return $this->belongsToMany(User::class);

    }
}
cbcw's avatar
Level 2

@automica I don't have a users/index.blade.php, but I do have the users.blade.php here ...

<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ __('Contact List') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">

                <table class="ml-5 mt-5 mb-5 table">
                    <thead>
                      <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Address</th>
                        <th>Child(dren)</th>
                        <th>Room</th>
                      </tr>

                      @foreach ($users as $user)

                      <tr>
                          <td>
                            {{ $user->title }} {{ $user->first_name }}
                            {{ $user->last_name }}
                          </td>
                          <td>
                            {{ $user->email }}
                            <br>
                            {{ $user->email2 }}
                          </td>
                          <td>
                            {{ $user->phone1 }}
                            <br>
                            {{ $user->phone2 }}
                          </td>
                          <td>
                            {{ $user->street_1 }}<br>
                            {{ $user->city }} {{ $user->state }} {{ $user->postal_code }}
                          </td>
                          <td>
                            @foreach ($user->kids() as $kid)
                                {{ $kid->id }}
                            @endforeach
                          </td>
                          <td>
                            Room 5<br>
                            Room 107
                          </td>
                      </tr>
                      @endforeach

                    </thead>



            </div>
        </div>
    </div>
</x-app-layout>
automica's avatar

@cbcw so are not getting any output for here?

    @foreach ($user->kids() as $kid)
                                {{ $kid->id }}
                            @endforeach
a4ashraf's avatar

@cbcw

use this in your kid model class, your problem will solve

 protected $guarded = [] // or even you use fillable
cbcw's avatar
Level 2

@automica No, just this error: "Trying to get property 'id' of non-object " and that is if I remove the "withDefault([]);" from my User model.

@a4ashraf When I add that into my Kid model it doesn't improve anything.

automica's avatar

@a4ashraf puzzling isnt it.

the only thing odd I can see is

$users = User::All();

that should be

$users = User::all();

but I didn't think that would make a real difference.

@cbcw can you switch your index to:

public function index()
    {
        $users = User::all(); // lower case A

        return view('users', ['users' => $users]);
    }
cbcw's avatar
Level 2

@automica

Same result.

I was searching the internet for days before finally posting on this forum. I'm somewhat relieved it wasn't a dumb mistake, but I also wish it was at the same time.

MichalOravec's avatar
Level 75

User model

public function kids()
{
    return $this->belongsToMany(Kid::class);
}

Controller

class UsersController extends Controller
{
    public function index()
    {
        $users = User::with('kids')->get();

        return view('users', compact('users'));
    }
}

View

@foreach ($users as $user)
    @foreach ($user->kids as $kid)
        {{ $kid->kid_first_name }}
    @endforeach
@endforeach
MichalOravec's avatar

I just use eager loading for that, because I don't know what he was trying to do before.

cbcw's avatar
Level 2

@michaloravec That did it! wow! You've made my day.

Can you point me towards some resources to help me learn why this works and what I was doing did not?

I definitely appreciate all the help from @a4ashraf and @automica ... You have been priceless and patient!

automica's avatar

@michaloravec he was just getting all users before without the eager load. I know the eager load is an optimization improvement don’t think it’s the issue here.

Is there a difference between Model::All() and Model::all() though?

Edit: so it looked like the eager load and get subsequent get was all that was different.

@cbcw how many rows are in your user table btw? If you do any extra work in this you’ll want to look at implementing pagination

1 like
MichalOravec's avatar

@automica It doesn't matter if it's Model::all() or Model::All() both works, but Model::All() is weird for me.

If you want to make a query or use eager loading etc. Everytime you have to use ->get(). all() you can just use to fetch all the data from table.

cbcw's avatar
Level 2

@automica For now, it's just faker data, so only 11 rows, and you are absolutely right - once I have real data it will be thousands of rows. Any hints or tips on pagination implementation would be most appreciated!

automica's avatar

@michaloravec i thought that was the case. Just puzzled why all() didn’t work and eager loading with the get() did.

Eager loading improves the performance of the query but without it shouldn’t prevent the relationship from working.

1 like
MichalOravec's avatar

Builder doesn't have all() method and when you use eager loading you work with query builder.

automica's avatar

So are you saying that without the eager loading you’d never be able to access the Model attached via the belongsToMany relationship?

My understanding is that it should work without eager loading but is less efficient with queries.

1 like
Previous

Please or to participate in this conversation.