How to Get Specific Attributes from Laravel Collection?

By Hardik Savani April 16, 2024 Category : Laravel

Today, i would like to show you laravel collection get specific columns. We will use laravel collection map with only() example. This post will give you simple example of laravel collection map get specific columns value. Here you will learn laravel collection only certain keys example.

Sometime we just need to get specific attributes from laravel collection. if you have many keys like id, name, price, details, body, status etc. and you just need to get id, name and price then how you will do?, i have solution how to get specific keys from collection. you can see bellow simple example

you can easily get specific attributes from collection in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 version app.

Example:

<?php

namespace App\Http\Controllers;

use App\Models\Product;

class SignaturePadController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$products = Product::get()

->map

->only(['id', 'name', 'price']);

dd($products);

}

}

Output:

Illuminate\Support\Collection Object

(

[items:protected] => Array

(

[0] => Array

(

[id] => 1

[name] => Laravel 8 Form Validation

[price] => 0

)

[1] => Array

(

[id] => 2

[name] => Laravel 8 CRUD

[price] => 0

)

[2] => Array

(

[id] => 3

[name] => Laravel 8 Ajax Form Validation

[price] => 0

)

.....

.....

I hope it can help you...

Shares