Home > Blockchain >  How to display two models in vue having a relationship
How to display two models in vue having a relationship

Time:07-01

Hi guys am having some trouble displaying 2 models having a relationship using vue as front end and laravel as my back end

I have this table book

book_table

this table belongs to author table

author_table

this is my Book Model in laravel

public function project(){
        return $this->belongsTo(Project::class);
    }

this is my laravel controller just a regular return on all the data from this 2 models

public function index()
    {
        $authors = Author::get();
        return response()->json([
            "authors" => $authors
        ], 200);

        
        $books = Books::get();
        return response()->json([
            "books" => $books
        ], 200);
    }

Now using vuetify v-for i want to display it like this

image

How can I achieve it. I don't want to change my database structure if possible

thanks

CodePudding user response:

As you have established your relation why don't eager load your relation in the query.

public function index(){
 
   $books=Book::with('author')->get();

   return response()->json([
            "books" => $books
        ], 200);
}

every book will have the author object embeded.

CodePudding user response:

do this on your Book class

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

and on your controller:

public function index(){
  $books=Book::with('author')->get();

  return response()->json([
        "books" => $books
  ], 200);
}
  • Related