N
N
Nurlan2017-04-27 23:18:20
Laravel
Nurlan, 2017-04-27 23:18:20

How to correctly request data from the model via json?

There is a User(belongsToMany) and Artist model.
The request User::find(1)->artists returns me a list of artists, everything is fine.
But when requesting this data via json:

return response()->json(['success'=>true,'user'=>User::find($user_id)]);

refuses to do so.
I add in the User model: It complains that there is no getArtistsAttribute() method , but if it is created, the data still does not return anything. But if you write a different name and method to it in appends, then both the artists and the invented field are returned to json, with duplicate content. What to do? How to get the field I need without dancing with a tambourine? Thank you. PS So far I solved the problem like this:
$appends=['artists'];

$user=User::find($user_id);
$user['artists']=$user->artists;
return response()->json(['success'=>true,'user'=>$user]);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
JhaoDa, 2017-04-27
@daager

You can not dance with a tambourine, but read the documentation about relationships , from which you can learn about methods with()and load().
And if you do not hesitate to open the code of the base model, then with = []you can find out about the property ...

S
Shamsudin Serderov, 2017-04-27
@Steein

//Первый
$user = User::find($user_id);

//Второй
$user = User::where('id', $user_id)->first();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question