1
votes

I'm supposed to display author details in bookformat method. But facing LogicException. Any suggestions thanks in advance. Im getting error like this LogicException in Model.php line 2709: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation. Any help that would be great for me. If I comment authors in bookFormat() everything works fine. But Idk why I'm unable to get author details in my bookformat().

#booksController.php
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Input;
    use App\Models\Book;
    use App\Models\Author;

    class BooksController extends Controller
    {
        public function index()
        {
            $books = Book::all();
            $results = [];
            foreach ($books as $book) {
             $results [] = $this->bookFormat($book);
         } 
         return $results; 
     }
        public function bookFormat($book){  
            return [ 
                'Id' => $book->id,
                'Title' => $book->title,
                'Author' => [ 
                    'Id' => $book->author->id,
                    'First_name' => $book->author->first_name,
                    'Last_name' => $book->author->last_name
                ],
                'Price' => $book->price,
                'ISBN' => $book->isbn,
                'Language' => $book->language,
                'Year' => $book->year_of_publisher
            ];
        }
    }

    //book.php
    namespace App\Models;
    use Illuminate\Database\Eloquent\Model;

    class Book extends Model
    {
        public $timestamps = TRUE;
        protected $table = 'books';
    //rules
        public static $rules = [
            'title' => 'required|max:255',
            'isbn' => 'required|max:50',
            'author_id' => 'required|max:255',
            'language' => 'required|max:255',
            'price' => 'required|max:255',
            'year_of_publisher' => 'required'
        ];
    //relationship
        public function author() {
            $this->belongsTo(Author::class);
        }
    }
1
awesome thanks @Marcin - steven
If it solves your issue please mark answer as accepted - Marcin Nabiałek
Can you explain how can I write this in the Inverse Of The Relationship?? Thanks in adv - steven
In Author class you can write public function books() { return $this->hasMany(Book::class); }. You should read Eloquent documentation for more details - Marcin Nabiałek

1 Answers

1
votes

Instead of:

public function author() {
    $this->belongsTo(Author::class);
}

you should have:

public function author() {
    return $this->belongsTo(Author::class);
}

Notice the return difference.