Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

alihoushyaripour's avatar

How to get data from left join as separate array instead of parameters?

Hi,

I need to get some data using DB:: from db, it's this:

$var = DB::table('places')
->leftJoin('phones', 'places.id', '=', 'phones.place_id')
->leftJoin('features', 'places.id', '=', 'features.place_id')
->take(1);

But response value is an object that contain all columns of these three table together and repetitive parameters replace with together. response that I want is this:

{
    "id",
    "name",
    // and other place parameters

    "phones": [
        {},
        ...
    ],

    "features": [
        {},
        ...
    ],
}

How can I make It ?!

0 likes
9 replies
tykus's avatar

Use Eloquent relationships instead of left joins:

Place::with(['phones', 'features'])->first();

Assumes you have the following relationships on the Place model:

public function phone()
{
    return $this->hasMany(Phone::class);
}

public function features()
{
    return $this->hasMany(Feature::class);
}
alihoushyaripour's avatar

@tykus My tables not define in my laravel project, I write this tables with php and mysql from ago, and now want to write them in my models and need to get them first and insert to models.

Is there any solution?

tykus's avatar

I don't understand. Are you saying you don't have these models written yet?

alihoushyaripour's avatar

@tykus No, I write my project 2 month ago with pure php and mysql, and now I want to switch to laravel framework and I need to insert my old db (in php project) to new db (in laravel project)

MikeRees's avatar

Can you not just continue using your existing database, and use Laravel's migrations to add Laravel infrastructure to it?

alihoushyaripour's avatar

@MikeRees Yes my friend, I change my database and tables schema, everything has changed! and then I was writed a seed class to insert old db data to the new one. My problem is in my seed class.

tykus's avatar

Why do you need a seed class to migrate the data from the old schema?

cmdobueno's avatar
Level 18

You can still write a model for a table you do not plan on keeping, just make a very simple model, set up the simple relationships, and then run the imports and then delete them.

I have done that countless times. It might seem like more work, but I found generally (when dealing with the requirement of joins or relationships) it is much faster... otherwise I just use DB::table("my_table")->get(); and do my insert that way.

1 like

Please or to participate in this conversation.