E
E
Emil Rakhmatullin2019-02-21 16:53:36
Laravel
Emil Rakhmatullin, 2019-02-21 16:53:36

How to fix Laravel "Trying to get property of non-object" error?

Route that sends data to the database:

Route::get('/admin', function () {
  $posts = DB::table('posts')->get();
  return view('admin-panel', compact('posts'));
});

The code that displays the categories:
@foreach ($posts as $posts)
                    @if( $posts->post_type == 'category' )
                      <tr>
                        <td>{{ $posts->title }}</td>
                        <td>
                          <button id="edit_category_{{ $posts->id }}" class="btn_edit danger"><i class="fa fa-trash-alt"></i></button>
                          <button id="remove_category_{{ $posts->id }}" class="btn_edit warning"><i class="fa fa-pencil-alt"></i></button>
                        </td>
                      </tr>
                    @endif
                  @endforeach

And the code that displays the products:
@foreach ($posts as $posts)
                      @if( $posts->post_type == 'product' )
                        <tr>
                          <td>{{ $posts->title }}</td>
                          <td>{{ $posts->description }}</td>
                          <td>{{ $posts->category }}</td>
                          <td>{{ $posts->code }}</td>
                          <td>{{ $posts->price }}₽</td>
                          <td>
                            <button id="edit_category_{{ $posts->id }}" class="btn_edit danger"><i class="fa fa-trash-alt"></i></button>
                            <button id="remove_category_{{ $posts->id }}" class="btn_edit warning"><i class="fa fa-pencil-alt"></i></button>
                          </td>
                        </tr>
                      @endif
                    @endforeach

When I remove the code for displaying categories or products, it works as it should. Why? How to re-call all this without errors?
Laravel latest version.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Dergachov, 2019-02-21
@Emchik

The cycle is written incorrectly

@foreach ($posts as $post)
    {{ $post->title }}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question