Yamona
Yamona

Reputation: 1130

Laravel API Routes manipulate the default JSON return

Let's say I have 2 tables. users & books. The tables look like this users:

id, name
1, Jone
2, Doe

books:

id, name, user_id
3, Dummy book1, 1
4, Dummy book2, 1
5, Dummy book3, 2

When I try to return all the books belong to a user (ex. user 1) like this

$query->where('id', 1)->join('books', 'users.id', '=', 'books.user_id');

I get JSON, BUT the issue is JSON display id for books not the user like this:

id: 3,//this is the book id not the user id
user_id: 1
...
...
id: 4,
user_id: 1

How I can make my query display the id as the user id like this

id:1
... whatever

Better yet, how I can manipulate the whole JSON so I can rename the keys? For example books.name to books_name and users.name to user_name I don't like the default JSON return

One of the reason I ask this that's if you join 2 tables or more the id will always be the last table.id

Upvotes: 1

Views: 178

Answers (2)

parker_codes
parker_codes

Reputation: 3397

I recommend using relationships the true Laravel way. So in your books model you would have a relation to the user. Then you can use the with('user') method on your query for eager loading the user! Way easier and cleaner!

Book::find($id)->with('user');

Using the find method is much better when working with IDs.

Then in your Book model:

public function user()
{
    return $this->belongsTo(User::class);
}

I do not actually know the relationship between the book and user so I am just guessing.

Another tip: if you are doing this in a controller, use Route Model Binding so that you don't have to even look up the book by its ID.

Upvotes: 1

Derek Pollard
Derek Pollard

Reputation: 7165

The easiest way to achieve what you want is to define the parameters in laravels built select:

$query->select(DB::raw("users.id AS user_id",), ...other rows you want to get back from the DB) 

Just make sure to define the parameters you need in the select.

Hope this helps!

Upvotes: 1

Related Questions