Bind user object to each article in laravel - php

here is in this example i fetch all category that has articles
and bind all articles to each category that belongs to like this
$categories = Category::has('articles')->with('articles')->get();
result
[
{
"id": 1,
"title": "Technology",
"created_at": "2019-09-22 16:58:24",
"updated_at": "2019-09-22 16:58:24",
"articles": []
},
{
"id": 2,
"title": "Programming",
"created_at": "2019-09-22 21:01:39",
"updated_at": "2019-09-22 22:36:17",
"articles": [{
"id": 10,
"title": "Intro To JavaScript",
"content": "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
"image": "articles/OUMvOY17KaqfcfK10c16UAcGegXeESopRw1hlxl9.png",
"user_id": 1,
"category_id": 2,
"created_at": "2019-09-22 22:35:10",
"updated_at": "2019-09-22 22:35:10"
}]
}
]
what I need is to bind also the user object for each article how can I make it

Maybe this can help you:
$categories = Category::has('articles')->with('articles' => function($query) {
$query->with('user');
})->get();
Hope it helps.

Related

How can loop & get values of unlimited parent-child & sub-child tree data in laravel

I have data like parent-child with unlimited levels of sub-child & sub-child data in the database which you can see below like a binary tree with nodes that have multiple children and these children can have unlimited sub-child.
Please give me a solution or suggestion how can show that. Thanks.
This is my database JSON data which I'm getting from the database...
Controller Code
$products = Product::where('project_id', $project_id )->whereNull('parent_id')->with('categories')->with('childProducts')->get();
Getting data from the above object this data want to save in the other way you can see below
{
"data": {
"products": [{
"id": 1,
"name": "ParentProduct",
"project_id": 1,
"parent_id": null,
"created_by": 1,
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00",
"categories": [{
"id": 6,
"product_id": 1,
"project_id": 1,
"name": "TopLevelCategory",
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00"
}],
"child_products": [{
"id": 2,
"name": "LevelOneProduct",
"project_id": null,
"parent_id": 1,
"created_by": null,
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00",
"categories": [{
"id": 1,
"product_id": 2,
"project_id": 1,
"name": "LevelOneProductCategory",
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00"
}],
"child_products": [{
"id": 3,
"name": "LevelOneProductChildFolder",
"project_id": null,
"parent_id": 2,
"created_by": null,
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00",
"categories": [{
"id": 2,
"product_id": 3,
"project_id": 1,
"name": "evelOneProductChildFolderCategory",
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00"
}],
"child_products": [{
"id": 4,
"name": "LevelOneProductSubChildFolder",
"project_id": null,
"parent_id": 3,
"created_by": null,
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00",
"categories": [{
"id": 3,
"product_id": 4,
"project_id": 1,
"name": "LevelOneProductSubChildFolderCategory",
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00"
}],
"child_products": []
}]
}]
},
{
"id": 5,
"name": "LeveTwoProduct",
"project_id": null,
"parent_id": 1,
"created_by": null,
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00",
"categories": [],
"child_products": [{
"id": 6,
"name": "LeveTwoProductFolder",
"project_id": null,
"parent_id": 5,
"created_by": null,
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00",
"categories": [{
"id": 4,
"product_id": 6,
"project_id": 1,
"name": "LeveTwoProductFolderCategory",
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00"
}],
"child_products": [{
"id": 7,
"name": "LeveTwoProductChildFolder",
"project_id": null,
"parent_id": 6,
"created_by": null,
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00",
"categories": [{
"id": 5,
"product_id": 7,
"project_id": 1,
"name": "LeveTwoProductChildFolderCategory",
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00"
}],
"child_products": []
}]
}]
}
]
}]
}
}
I want to take this data to another JSON data which I have to give you an example as mentioned below I want to loop the above JSON data and want to make their need JSON with this data as like Dear Problem is that How can loop above data and can give to the other JSON keys you can see below. I want all data with loop and want to get all values and want equal all values to the keys as below
foreach ($products as $product) {
foreach ($product->categories as $singleCaegory) {
$singleCaegoryData = [
"name" => $singleCaegory->name,
"request" => [
'method' => $singleCaegory->type,
'body' => [
"mode" => "raw",
'raw' => $singleCaegory->raw_data
],
'url' => [
"raw" => $singleCaegory->url
],
],
];
}
}
I think you understand my problem. that I want to loop above data which I have already in the database and fetching from that. I only want to loop all data and equal to the needed keys. Thanks.
for saving Id's you only need:-parent Id, child_Id_count(count of the only direct child), total_child_count(count all children below).that's it by using these data and created date you can generate a tree view.

In Laravel, how to combine where() and orderBy() when orderBy() is working on relationship?

I have two Models, a Track model and an Artist model, where each Track model belongsTo() one Artist model. Track models have a number column and Artist models have a name column. I want to retrieve all Tracks where number = 1 and then display those sorted by their Artist's name. So far I have only figured out how to do one or the other, but not both.
I would expect to be able to do this with something like:
Track::with(['artist' => function($q) {
$q->orderBy('name');
}])->where('number', 1)->get();
This displays all tracks where number = 1, but the tracks are not sorted in any particular order. I get the same result if I remove the with() altogether. Conversely, if I remove the where() clause then I get all Tracks in the database, and they are sorted by the Artist's name. How can I combine these two functions? The results should look like:
[
{
"id": 17,
"created_at": "2019-09-04 22:33:50",
"updated_at": "2019-09-04 22:33:50",
"number": 1,
"title": "Iste omnis maxime inventore rerum nam et.",
"artist_id": 2,
"album_id": 4,
"length": "06:08",
"disc_number": 1,
"artist": {
"id": 2,
"created_at": "2019-09-04 22:33:46",
"updated_at": "2019-09-04 22:33:49",
"name": "Ace",
"image_id": "4"
}
},
{
"id": 35,
"created_at": "2019-09-04 22:33:54",
"updated_at": "2019-09-04 22:33:54",
"number": 1,
"title": "Doloremque quidem voluptatibus doloribus et.",
"artist_id": 4,
"album_id": 7,
"length": "18:13",
"disc_number": 3,
"artist": {
"id": 4,
"created_at": "2019-09-04 22:33:46",
"updated_at": "2019-09-04 22:33:53",
"name": "Bar",
"image_id": "10"
}
},
{
"id": 54,
"created_at": "2019-09-04 23:00:08",
"updated_at": "2019-09-04 23:00:08",
"number": 1,
"title": "Ut placeat assumenda aut.",
"artist_id": 21,
"album_id": 17,
"length": "09:25",
"disc_number": 4,
"artist": {
"id": 21,
"created_at": "2019-09-04 23:00:08",
"updated_at": "2019-09-04 23:00:08",
"name": "Cat",
"image_id": "22"
}
},
{
"id": 71,
"created_at": "2019-09-04 23:00:11",
"updated_at": "2019-09-04 23:00:11",
"number": 1,
"title": "Omnis et dolores odio a eius.",
"artist_id": 22,
"album_id": 20,
"length": "16:48",
"disc_number": 2,
"artist": {
"id": 22,
"created_at": "2019-09-04 23:00:08",
"updated_at": "2019-09-04 23:00:10",
"name": "Dog",
"image_id": "25"
}
},
]
Use something like this:
Track::with('artist')->join('artist', 'artist.id', '=', 'track.artist_id')->orderBy('artist.name', 'DESC')->get()
I hope you getting my point
You cannot sort by artist's name with your code because laravel, to eager load artists with tracks, executes two queries, you should use a join to have one query but I give two other options (I don't like joins):
1) You can use sortBy() or sortByDesc() (if you want to sort descending) on the resulting collection, e.g.:
$tracks = Track::with('artist')->where('number', 1)->get()->sortBy('artist.name');
2) You can start querying from Artist, but you have to change a bit your view, e.g.:
$artists = Artist::with(['tracks' => function($q) {
$q->where('number', 1);
}])->orderBy('name')->get();
3) You can use joins, see another answer please.
FYI if you want to debug a query just append ->toSql() in place of ->get() to get a string of your SQL.

Get query instead of replace foreign key by name in laravel

Get query instead of replace foreign key by name in laravel.Get record replacement of menu_id to menu_name.Menu table contains id and menu_name.
"cart_items": [
{
"id": 1,
"cart_id": 1,
"menu_id": 5,
"quantity": "3",
"amount": "150",
"created_at": "2019-09-04 09:45:28",
"updated_at": "2019-09-04 09:45:28"
},
{
"id": 2,
"cart_id": 1,
"menu_id": 4,
"quantity": "3",
"amount": "150",
"created_at": "2019-09-04 09:54:32",
"updated_at": "2019-09-04 09:54:32"
}
]
use Laravel mutators to add menu_name for object, and add menu_id to $hidden =['manu_id']; in the model class
I use with method while fetching query.Its works
$data['cart_items'] = CartItem::with('menu')->where('cart_id',$cart->id)->get();
In my CartItem model i use eloquent orm function:
public function menu()
{
return $this->hasOne('App\Menu','id','menu_id')->select(['id','menu_name']);
}
It returns output:
"cart_items": [
{
"id": 1,
"cart_id": 1,
"menu_id": 5,
"quantity": "3",
"amount": "150",
"created_at": "2019-09-04 09:45:28",
"updated_at": "2019-09-04 09:45:28",
"menu": {
"id": 5,
"menu_name": "PODI IDLI"
}
},
{
"id": 2,
"cart_id": 1,
"menu_id": 4,
"quantity": "3",
"amount": "150",
"created_at": "2019-09-04 09:54:32",
"updated_at": "2019-09-04 09:54:32",
"menu": {
"id": 4,
"menu_name": "CORN PANEER MIX VEG SALAD WITH SAUSAGE"
}
}]

Rejecting certain index parameters in an array

Given an array, in which each index there are certain key value pairs, how do I select certain key value pairs and reject the others.
$channels = Channel::get()->toArray();
This will yield the following Array:
"channels": [
{
"id": 1,
"name": "Info Release",
"slug": "info-release",
"desc": "Contains blah blah.",
"access_level": "0",
"created_at": "2018-12-02 01:23:50",
"updated_at": "2018-12-05 07:54:41"
},
{
"id": 11,
"name": "Casual News",
"slug": "casual-news",
"desc": "Contains blah blah.",
"access_level": "0",
"created_at": "2018-12-05 05:34:50",
"updated_at": "2018-12-05 07:54:32"
},
{
"id": 12,
"name": "haha",
"slug": "haha",
"desc": "Contains blah blah.",
"access_level": "0",
"created_at": "2018-12-29 23:27:16",
"updated_at": "2018-12-29 23:27:16"
}
],
What is the best way to turn that array into this:
"channels": [
{
"id": 1,
"name": "Information Release",
"slug": "information-release",
},
{
"id": 11,
"name": "Casual News",
"slug": "casual-news",
},
{
"id": 12,
"name": "haha",
"slug": "haha",
}
],
So that if I write
$channels[0]->id
it will spit out 1
Can You try this
$viewFileds = ['id', 'name', 'slug'];
$channels = Channel::get()
->map(function ($each) use ($viewFileds) {
return Arr::only($each, $viewFileds);
});
It will return the new Collection by Only the field enabled in the $viewFileds
Hope it helps

Laravel 5.2: extracting nested collection

I am working on Laravel 5.2 application. I'm having an issue in extracting the nested collection from the parent collection. I'm trying to get all the posts from the users whom I am following like this:
$posts = \Auth::user()->following()->get()->each(function($following){
return $following->posts;
});
But it is returning me a collection of the users I am following and the posts collection is nested in this collection, such that:
[
{
"id": 2,
"name": "John Doe",
"username": "john",
"email": "johny#example.com",
"created_at": "2016-03-08 11:06:45",
"updated_at": "2016-03-08 11:06:45",
"pivot": {
"follower_id": 1,
"followee_id": 2
},
"posts": [
{
"id": 1,
"user_id": 2,
"title": "Post title 1",
"created_at": "2016-03-08 11:09:22",
"updated_at": "2016-03-08 11:09:22"
},
{
"id": 3,
"user_id": 2,
"title": "Post title 2",
"created_at": "2016-03-09 08:04:18",
"updated_at": "2016-03-09 08:04:18"
}
]
}
]
How can I get all the posts from the all of the users I'm following as a collection?
Any help will be appreciated
$posts = [];
\Auth::user()->following()->get()->each(function($following) use(&$posts){
array_push($posts, $following->posts)
});
Hope this helps.

Categories