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
Please see:
Once you properly define your model relations, you can use
with
function to pull additional data with your base model:You have to make proper relations in model first.
Book.php
Contribution.php
Now you should be able to use these relationships in controller like this:
In contributors array, you need to make relations again in the respective model to get the name of author.