How to Get Specific Attributes from Laravel Collection?

By Hardik Savani | March 8, 2021 | 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 and laravel 8 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...




Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.

We are Recommending you: