Fetch Only Specific Attributes From Table In Laravel

Hello devs in this brand new example i will share with you that how we can get only our selected specific column from laravel collection query. That when we fetch data from laravel table, many time we didn't need all the attributes from a table. In this situation we need specific column.

So for this reason i am here to share with you that how to get specific attributes from Laravel collection query? So if you don't know that query of how to get specific attributes in laravel 8 the this example is for you.

Example one:

public function index()
{
  $products = Product::get()
                 ->map
                 ->only(['id','price']);
}

 

Example two:

public function index()
{
  $products = Product::select('id','name','price')->get();
}

 

Example three:

public function index()
{

  $collection = Product::all();

  return [
		'data' => $collection->map(function($data) {
			return [
				'id'      => $data->id,
				'name'    => $data->name,
				'price'   => $data->price
			];
	   })
  ];
}

 

Read also: Run Cron Job Based on Condition in Laravel

 

Hope it can help you.

 

#laravel #laravel-8x #eloquent-tips