How to Get Specific Attributes from Laravel Collection?

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Hello Dev’s. Today I will show How to Get Specific Attributes from Laravel Collection. I will like to show you laravel collection get specific columns from database table. Here we will use laravel collection map with only() example for this tutorial. So now this post i will give you a very simple example of how to laravel collection map get specific columns value. Here we can learn laravel collections of only certain keys example.

So sometime we need to get just specific attributes from laravel collection. If you have many keys as like as id, name, price, details, body, status etc. and if you need to get just id, name and price then how we can will do? I have s good solution for how to get specific keys from collection. You can see it bellow with a short and simple example

So you can easily get specific attributes from collection in laravel 6, laravel 7 and laravel 8 version application.

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);
    }
}

Read Also : How to Setup Typescript in Laravel Vue Application?

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

                )

Read Also : How to check array is empty or null or undefined in javascript?

I hope it will help you.For more you can follow us on facebook

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →