Nick W
Nick W

Reputation: 917

How to add array to Laravel db result row?

My code returns the first row from a Laravel $data = DB::table('sometable')->select('id')->get(); using:

$row = $data->first();

I can then return id using:

$row->id;

How can I now add an array with key 'moredata' to that row collection object for referencing later in the code? I've tried:

$row->put('moredata', $moredata);

Where $moredata is a populated array and 'moredata' is not a field in the table. Laravel throws the error 'Call to undefined method stdClass::put()'. I could convert to an array and simply extend the array, just wondered if it could be done retaining the Laravel collection structure?

Upvotes: 0

Views: 3244

Answers (4)

jjj
jjj

Reputation: 187

You can append data: https://laravel.com/docs/5.4/eloquent-serialization#appending-values-to-json

Occasionally, when casting models to an array or JSON, you may wish to add attributes that do not have a corresponding column in your database.

Upvotes: 0

vipin
vipin

Reputation: 2510

try this :

$data = DB::table('sometable')->select('id')->first();
$data->moredata = $moredata;

or

$data = DB::table('sometable')->select('id')->get();
$data = $data[0];
$data->moredata = $moredata;

Upvotes: 0

Sanni
Sanni

Reputation: 1

<?php
$appends = ['moredata']

function getMoredataAttribute() {
    return ['data' => '...data...'];
}

put this into your Model

Upvotes: 0

Jerodev
Jerodev

Reputation: 33216

You can just set the property on the object directly.

$row = DB::table('sometable')->select('id')->first();
$row->moredata = $moredata;

Also, If you only need one record, use the first function on your query builder. Otherwise, you will query the database for all records and filter the first in memory.

Upvotes: 1

Related Questions