In addition to findOrFail()
, there's also Eloquent method firstOrFail()
which will return 404 page if no records for query are found.
The findOrFail
method in Laravel is a powerful tool when it comes to retrieving records from your database. It's commonly used to fetch a specific record by its primary key and throw an exception if the record is not found.
$user = User::where('email', '[email protected]')->firstOrFail();
Laravel's Eloquent Query Builder, you can use the as
method to specify an alias for a column, just like you would in a plain SQL query. This feature is particularly useful when you need to rename a column for readability, and consistency, or when dealing with calculated values. Here's how you can use it:
$results = DB::table('users')
->select('email as user_email')
->get();
After executing an Eloquent query, you can modify the retrieved rows by using the map()
function on the resulting collection.
$users = User::where('role_id', 1)->get()->map(function (User $user) {
$user->some_column = some_function($user);
return $user;
});
By default, Laravel assumes that your database table has created_at
and updated_at
columns for timestamp tracking. However, you can customize these field names on a per-model basis using the $createdAt
and $updatedAt
properties in your Eloquent model.
class User extends Model
{
// Specify custom field names for timestamps
const CREATED_AT = 'custom_created_at';
const UPDATED_AT = 'custom_updated_at';
}
In Laravel, you can easily retrieve records from your database ordered by the created_at
column in ascending or descending order using the orderBy
method. Here's how to do it:
Instead of:
$records = User::orderBy('created_at', 'desc')->get();
You can do it:
User::latest()->get();
There is an opposite method oldest()
which would order by created_at
ascending:
User::oldest()->get();
Additionally, you can specify another column to order by. For example, if you want to use updated_at
, you can do so like this:
$lastUpdatedUser = User::latest('updated_at')->first();
If you want to generate a database column value when creating a record, you can add this logic to the model's boot()
method. For instance, if you have a field named 'position' and wish to assign the next available position to a new record, such as Country::max('position') + 1
, you can achieve it like this:
class Country extends Model {
protected static function boot()
{
parent::boot();
Country::creating(function($model) {
$model->position = Country::max('position') + 1;
});
}
}
To leverage SQL raw queries, such as the whereRaw()
method, you can perform database-specific calculations directly within your query. This approach can often yield faster results. For instance, if you need to retrieve users who have been active for 30 or more days since their registration, consider using the following code as an example:
User::where('active', 1)
->whereRaw('TIMESTAMPDIFF(DAY, created_at, updated_at) > ?', 30)
->get();
In Eloquent, you have the flexibility to combine and chain multiple query scopes together, allowing you to use more than one scope in a single query. This feature enables you to construct complex queries while keeping your code organized and maintainable.
Model:
class Product extends Model
{
// Scope to retrieve active products
public function scopeActive($query)
{
return $query->where('status', 'active');
}
// Scope to retrieve discounted products
public function scopeDiscounted($query)
{
return $query->where('discounted', true);
}
// Scope to order products by popularity (assuming you have a 'popularity' column)
public function scopePopular($query)
{
return $query->orderBy('popularity', 'desc');
}
}
Now, you can use these scopes to build your query:
$products = Product::active()
->discounted()
->popular()
->get();
When using whereDate()
to filter records for today, you can utilize Carbon's now()
method, and it will automatically be transformed into a date. There's no need to explicitly call ->toDateString()
.
// Instead of
$todayUsers = User::whereDate('created_at', now()->toDateString())->get();
// No need to convert, just use now()
$todayUsers = User::whereDate('created_at', now())->get();
You might also like:
- Read Also: Laravel tips: DB Models and Eloquent - Part 2
- Read Also: Laravel 9 Left Join Query Example
- Read Also: Laravel 9 Inner Join Query Example
- Read Also: Laravel 9 Many To Many Polymorphic Relationship