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

UsmanBasharmal's avatar

Laravel modal query

I am trying to get array of related model to my data and it returns null.

Code

return Product::with(['allBarcodes' => function ($query) {
  $query->select('serial_number');
}])->get();

result

one

Also I tried pluck like $query->pluck('serial_number'); and result was

two

My real data

the data I suppose to receive is like

[{
  "id":1,
  "product_id":1,
  "serial_number":"5245412185", // I only need this to be return as array
  "sold":1,
  "created_at":"2020-05-24T04:21:56.000000Z",
  "updated_at":"2020-05-24T04:21:56.000000Z"
}]

Any idea?

0 likes
3 replies
UsmanBasharmal's avatar

I found the solution

When I was doing this $query->select('serial_number'); I was only selecting serial_number and not the column that connects both the modals i.e. product_id inside barcodes table.

$query->select('product_id', 'serial_number');. However this will return 2 columns. If somebody wants just one then he/she will have to use [collection transform][1].

$products = $products->map(function ($product) {
    $product->allBarcodes->transform(function ($q) {
        return $q->serial_number;
    });
    return $product;
});
AndrykVP's avatar

It would depend on where you want this attribute to be appended. If you want your serial_number attribute whenever you retrieve a model, I would suggest this: https://laravel.com/docs/7.x/eloquent-serialization#appending-values-to-json

In your App\Product.php file, add the following:


    protected $appends = ['serial_number'];

    public function getSerialNumberAttribute()
    {
        return $this->allBarcodes->serial_number;
    }

or if your relationship to barcodes is a One to Many or Many to Many then loop through the collection like this:


    public function getSerialNumberAttribute()
    {
        $result = [];

        foreach($this->allBarcodes as $barcode)
        {
            array_push($result,$barcode->serial_number);
        }

        return result;
    }
UhOh's avatar

All fair options. Also, I know it’s not sexy, but it’s worth remembering you can do DB statements and simply do your joins, etc. I think as Laravel devs we get a bit too attached with Eloquent.

Please or to participate in this conversation.