How to get the value from laravel collection?

Member

by daisha , in category: PHP Frameworks , 6 months ago

How to get the value from laravel collection?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 6 months ago

@daisha 

To get the value from a Laravel collection, you can use the first() method if you want to get the first item in the collection, or you can use the get() method with the key of the value you want to retrieve.


For example, if you have a collection of user data and you want to get the email of the first user in the collection, you can do the following:

1
2
3
$users = User::all();

$firstUserEmail = $users->first()->email;


If you want to get a specific value from a collection based on a key, you can use the get() method like this:

1
2
3
$users = User::all();

$userEmail = $users->get(3)->email;


In the above example, we are getting the email of the user at index 3 from the collection.


You can also use the pluck() method to retrieve a specific column from the collection. For example, to get all the email addresses from a collection of users, you can do the following:

1
2
3
$users = User::all();

$emails = $users->pluck('email');


This will return a new collection containing only the email addresses of the users.