Answer the question
In order to leave comments, you need to log in
How to make one with an additional parameter from two collections?
Hello everybody! I need your help.
Essence of the question: how to get one from two collections, namely, if the field (id) matches, add a field to the output collection Code example:"is_follow" => true/false
$tags = Tag::all();
$user_tags = auth()->user()->tags()->get();
$tags = Tag::all()
- All tags $user_tags = auth()->user()->tags()->get()
- Tags that the current user is followingdd($tags->toArray());
array:50 [
0 => array:6 [
"id" => 1
"icon" => "https://picsum.photos/seed/id/100/100"
"title" => "Id"
"slug" => "id"
"created_at" => "2021-08-06T14:22:15.000000Z"
"updated_at" => "2021-08-06T14:22:15.000000Z"
]
1 => array:6 [
"id" => 3
"icon" => "https://picsum.photos/seed/qui/100/100"
"title" => "Qui"
"slug" => "qui"
"created_at" => "2021-08-06T14:22:15.000000Z"
"updated_at" => "2021-08-06T14:22:15.000000Z"
]
...
]
dd($user_tags->toArray());
array:2 [
0 => array:7 [
"id" => 1
"icon" => "https://picsum.photos/seed/nesciunt/100/100"
"title" => "Nesciunt"
"slug" => "nesciunt"
"created_at" => "2021-08-06T14:22:15.000000Z"
"updated_at" => "2021-08-06T14:22:15.000000Z"
"pivot" => array:2 []
]
1 => array:7 [
"id" => 3
"icon" => "https://picsum.photos/seed/nulla/100/100"
"title" => "Nulla"
"slug" => "nulla"
"created_at" => "2021-08-06T14:22:15.000000Z"
"updated_at" => "2021-08-06T14:22:15.000000Z"
"pivot" => array:2 []
]
array:50 [
0 => array:7 [
"id" => 1
"icon" => "https://picsum.photos/seed/id/100/100"
"is_follow" => true
"title" => "Id"
"slug" => "id"
"created_at" => "2021-08-06T14:22:15.000000Z"
"updated_at" => "2021-08-06T14:22:15.000000Z"
]
1 => array:7 [
"id" => 2
"icon" => "https://picsum.photos/seed/qui/100/100"
"is_follow" => false
"title" => "Qui"
"slug" => "qui"
"created_at" => "2021-08-06T14:22:15.000000Z"
"updated_at" => "2021-08-06T14:22:15.000000Z"
]
2 => array:7 [
"id" => 3
"icon" => "https://picsum.photos/seed/qui/100/100"
"is_follow" => true
"title" => "Qui"
"slug" => "qui"
"created_at" => "2021-08-06T14:22:15.000000Z"
"updated_at" => "2021-08-06T14:22:15.000000Z"
]
...
]
Answer the question
In order to leave comments, you need to log in
$user_tags = auth()->user()->tags()->pluck('id');
$tags = Tag::all()->each(function (Tag $tag) use ($user_tags): Tag {
$tag->setAttribute('is_follow', $user_tags->contains($tag->id))
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question