Trying to get property of non-object


I try to solve my error, but I don't find solution. I try to get all exercises in my table exercises with three foreign key with types table, equipment table and muscle table. Trying to get property of non-object

My views code :


           @foreach($exercises as $exercise)
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title">
                        <a class="text-dark" href="exercise/{{ $exercise->id }}">{{ $exercise->name }}</a>
                <div class="card-body">
                   <div class="row">
                      <div class="media">
                          <?php if( $exercise->mediatype == 0) {?>
                              <img class="align-self-center mr-3" src="/images/exercises/{{ $exercise->mainmedia }}" style="width: 320px; height: 320px;">
                            <?php }else{ ?>
                                <video class="align-self-center mr-3" width="320" height="240" controls>
                                  <source src="/video/{{ $exercise->mainmedia }}" type="video/mp4">
                            <?php } ?>
                          <div class="media-body">
                            <div class="mt-0 row"><p>Équipement : </p>{{ $exercise->equipment->name }}</div>
                            <div class="mt-0 row"><p>Type : </p>{{ $exercise->type->name }}</div>
                            <div class="mt-0 row"><p>Muscle principal : </p>{{ $exercise->muscle->name }}</div>

My function on the controller :

public function index()
        $exercises = Exercises::with('equipment', 'type', 'muscle')->get();

        return view('exercises')->with(compact('exercises'));

Where is my error?

Firtzberg replied 1 year ago


Looks like $exercise->muscle is not an object, it might be null.

Sign in to participate in this thread!

We'd like to thank these amazing companies for supporting us