You can group Eloquent results based on any custom condition. In this guide, we'll illustrate how to group results by the first letter of a user's name.
$users = User::all()->groupBy(function($item) {
return $item->name[0];
});
Welcome to the fourth installment of our "Laravel Tips: DB Models and Eloquent" series. In this article, we continue our journey into the powerful world of Laravel's Eloquent ORM and database models.
By now, you've likely grasped the fundamentals of Laravel's Eloquent, and in this part, we'll delve into more advanced techniques and best practices to help you become a Laravel Eloquent.
Eloquent, the eloquent ORM (Object-Relational Mapping) component of the Laravel framework, is known for its simplicity, expressiveness, and developer-friendly features.
So, let's see Laravel Tips DB Models and Eloquent - 2023, Laravel 9 Tips and Tricks, Laravel 10 Tips and Tricks, Laravel 10 Eloquent Query, Laravel groupBy, Use UUID instead of auto-increment.
You can group Eloquent results based on any custom condition. In this guide, we'll illustrate how to group results by the first letter of a user's name.
$users = User::all()->groupBy(function($item) {
return $item->name[0];
});
If you have a database column that should be set only once and remain immutable, you can enforce this constraint using an Eloquent model mutator.
In version 9 or 9+.
use Illuminate\Database\Eloquent\Casts\Attribute;
class User extends Model
{
protected function email(): Attribute
{
return Attribute::make(
set: fn ($value, $attributes) => $attributes['email'] ?? $value,
);
}
}
In version 9 and below:
class User extends Model
{
public function setEmailAttribute($value)
{
if (isset($this->attributes['email']) && ! is_null($this->attributes['email'])) {
return;
}
$this->attributes['email'] = $value;
}
}
The Eloquent find()
method is versatile, as it can accept multiple parameters to retrieve multiple records from the database. When used in this way, it returns a collection containing all the records found, rather than just a single Eloquent model instance.
// Will return Eloquent Model
$user = User::find(1);
// Will return Eloquent Collection
$users = User::find([1,2,3]);
return Product::whereIn('id', $this->productIDs)->get();
// You can do this
return Product::find($this->productIDs)
Incase of integers, use whereIn
with limited data range only instead use whereIntegerInRaw
which is faster then whereIn
.
Product::whereIn('id', range(1, 50))->get();
// You can do this
Product::whereIntegerInRaw('id', range(1, 50))->get();
The Eloquent find()
method can accept multiple parameters, and in doing so, it returns a collection of all records found with the specified columns, rather than retrieving all columns of the model.
// Will return Eloquent Model with first_name and email only
$user = User::find(1, ['first_name', 'email']);
// Will return Eloquent Collection with first_name and email only
$users = User::find([1,2,3], ['first_name', 'email']);
You can also find multiple records using the whereKey()
method, which automatically considers the primary key field. By default, Eloquent uses 'id' as the primary key, but you can override this setting in your Eloquent model if needed.
$users = User::whereKey([1,2,3])->get();
You don't want to use auto incrementing ID in your model.
Migration:
Schema::create('users', function (Blueprint $table) {
// $table->increments('id');
$table->uuid('id')->unique();
});
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use HasUuids;
// ...
}
$article = Article::create(['title' => 'Traveling to Europe']);
$article->id; // "8f8e8478-9035-4d23-b9a7-62f4d2612ce5"
Starting from Laravel 6, you can enhance your Eloquent statements with the addSelect()
method, allowing you to include additional columns in your query and perform calculations on those added columns.
return Destination::addSelect(['last_flight' => Flight::select('name')
->whereColumn('destination_id', 'destinations.id')
->orderBy('arrived_at', 'desc')
->limit(1)
])->get();
When performing an Eloquent query and you want to exclude a specific field from the results, one of the quickest methods is to use ->makeHidden()
on the collection result. This allows you to hide or exclude the desired field without altering the model's structure.
$users = User::all()->makeHidden(['email_verified_at', 'deleted_at']);
If you need to catch exceptions related to Eloquent queries, it's advisable to use the specific QueryException
class instead of the default Exception
class. This approach enables you to access the precise SQL error code, aiding in the troubleshooting and debugging of database-related issues.
try {
// Some Eloquent/SQL statement
} catch (\Illuminate\Database\QueryException $e) {
if ($e->getCode() === '23000') { // integrity constraint violation
return back()->withError('Invalid data');
}
}
It's important to keep in mind that when using Eloquent to retrieve records, soft-deleted entries are automatically excluded. However, when you use the Query Builder directly, soft-deletes are not applied by default.
// Will exclude soft-deleted entries
$users = User::all();
// Will NOT exclude soft-deleted entries
$users = User::withTrashed()->get();
// Will NOT exclude soft-deleted entries
$users = DB::table('users')->get();
You might also like:
In this article, we will see how to count days between two dates in PHP excluding weekends. Here, we will learn to...
Jan-25-2023
In this article, we will fix the laravel 9 form class not found error, many times we have received errors like lara...
Sep-19-2022
Hello, laravel web developers! In this article, we'll see how to create a Google autocomplete address in laravel 11....
Jun-26-2024
In this article, we will see carbon diffForHumans in laravel. Carbon diffForHumans function in carbon provides the...
Dec-14-2020