Laravel Trying to get property of non-object when i get data

- 1 answer

Ad

i get this error when i get section data and the problem with section result part the book part and author part working good when i remove section part it working with out section_name Laravel Framework version 5.1.25 (LTS)

Trying to get property of non-object (View: C:\xampp\htdocs\lib\resources\views\libraryViewsContainer\summary.blade.php)

my Book Model

class Book extends Model
{
    public function section()
    {
        return $this->belongsTo('App\Section','id');
    }

    public function author()
    {
        return $this->belongsToMany('App\Author','books_authors_relationship','book_id','author_id')->withTimestamps();
    }

my BooksController

public function summary(){
        $all_results = Book::with('section')->with('author')->get();
        return view('libraryViewsContainer.summary',compact('all_results',$all_results));
    }

my summary blade

    <div class="container">
        <h1 class="well text-center">Library Summary</h1>
        <table class="table">
            <tr>
                <th style="width: 25%">Section Name</th>
                <th style="width: 25%">Book Title</th>
                <th style="width: 25%">Book Description</th>
                <th style="width: 25%">Authors</th>
            </tr>

            @foreach($all_results as $bookModel)
                <tr>
                    <td>
                        <a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="/section/{{$bookModel->section->id}}">
                        <span class="label label-info">{{$bookModel->section->section_name}}</span>
                        </a>
                    </td>
                    <td>
                        {{$bookModel->book_title}}
                    </td>
                    <td>
                        {{$bookModel->book_description}}
                    </td>
                    <?php $authors = $bookModel->author; ?>
                    <td>
                        @foreach($authors as $author)
                            <a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="/author/{{$author->id}}">
                                <span class="label label-danger">{{$author->first_name}} {{$author->last_name}}</span>
                            </a>
                        @endforeach
                    </td>
                </tr>
            @endforeach
        </table>
    </div>
@stop
Ad

Answer

Ad

the error was in Book model i changed

public function section()
    {
        return $this->belongsTo('App\Section','id');
    }

to

return $this->belongsTo('App\Section');

and it worked thanks for all help me

Ad
source: stackoverflow.com
Ad