0

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?

1
  • $row->moredata = $moredata; Commented Sep 1, 2017 at 11:21

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0
<?php
$appends = ['moredata']

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

put this into your Model

Comments

0

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;

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.