skip to Main Content

Im learning the MVC pattern using Laravel and the eloquent model is kinda overwhelming to me. The eloquent model returns a collection of collumns of a table, but i want to a collection of another table to be the attributes of that model.

I have 3 tables

Books
id,
title

Contribution
book_id,
contributor_id,
role

Author
id,
name

I want to change the return values of function like all(), find(), get() and etc of model Books to include the contributors

From this

[  "id" => "1", 
   "title" => "CS101" 
]

To this

[ "id" => "1",
  "title" => "CS101",
  "contributors" => [
   [
    "id" => "1",
    "name" => "Einstein"
    "role" => "author"
   ],
   [
    "id" => "2",
    "name" => "Thomas"
    "role" => "translator"
   ]
  ]
]

Should i not use Eloquent and build my own model or is there a function of eloquent that i can override or any better way to do this

2

Answers


  1. Please see:

    Once you properly define your model relations, you can use with function to pull additional data with your base model:

    $books = Book::with('author')->get();
     
    foreach ($books as $book) {
        echo $book->author->name;
    }
    
    Login or Signup to reply.
  2. You have to make proper relations in model first.

    Book.php

    public function contributors() {
       return $this->hasMany( Contribution:class );
    }
    

    Contribution.php

    public function books() {
     return $this->belongsTo( Book:class );
    }
    

    Now you should be able to use these relationships in controller like this:

    $books = Book::with('contributors')->get();
    

    In contributors array, you need to make relations again in the respective model to get the name of author.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search