return an associative array using laravel query builder

457
August 07, 2017, at 4:25 PM

I want to fetch a post along with its associate images. My query returns results as follows:

query

$result =  DB::table('posts')
            ->join('users', 'users.id', '=', 'posts.user_id')
            ->join('post_images', 'post_images.post_id', '=', 'posts.id')
            ->select('users.name', 'posts.*', 'post_images.image')
            ->where([
               'users.id' => 1,
               'posts.id' => 38
            ])
            ->get();
dd($result);

output

I want all images associated with the post populate as an associative array of single collection/result. For example for ID 38 instead of 2 result as above image i need as follows:

array:49 [▼
  0 => {#205 ▼
    +"name": "wahid"
    +"id": 38
    +"user_id": 1
    +"categories_id": 1
    +"body": "something !!"
    +"color": "LightGreen"
    +"mood": "Loved"
    +"created_at": "2017-08-07 01:15:48"
    +"updated_at": "2017-08-07 01:15:48"
    +"images" => array:3 [
        0 => 'image1.jpg'
        1 => 'image2.jpg'
        2 => 'image3.jpg'
    ]
  }

thanks for the help.

Answer 1

Try to group by posts id :

$result =  DB::table('posts')
            ->join('users', 'users.id', '=', 'posts.user_id')
            ->join('post_images', 'post_images.post_id', '=', 'posts.id')
            ->select('users.name', 'posts.*', 'post_images.image')
            ->where([
               'users.id' => 1,
               'posts.id' => 38
            ])
            ->groupBy('posts.id')
            ->get();
dd($result);
Answer 2

Try this:

use ->get()->toArray();

$result =  DB::table('posts')
            ->join('users', 'users.id', '=', 'posts.user_id')
            ->join('post_images', 'post_images.post_id', '=', 'posts.id')
            ->select('users.name', 'posts.*', 'post_images.image')
            ->where([
               'users.id' => 1,
               'posts.id' => 38
            ])
            ->get()->toArray();
dd($result);
Rent Charter Buses Company
READ ALSO
Sent email attachment using mailgun library, codeigniter

Sent email attachment using mailgun library, codeigniter

Can anyone please guide me how to send an attachment using mailgun and codeigniterSearching it from last 3 days and not finding any proper clue that how deal with it

265
How to count number of grandchildren of a model in Laravel 5?

How to count number of grandchildren of a model in Laravel 5?

Let say I have a database like the following:

358
How to get high-res thumbnails out of low-res SVGs in Mediawiki?

How to get high-res thumbnails out of low-res SVGs in Mediawiki?

I don't exactly know how to word this question properly, so I'll make an attempt:

298
Filter specific column in array in php

Filter specific column in array in php

I am trying to filter a specific column in an array in php using the code below:

259