Laravel Eloquent Functions !

Soulaimaneyh
6 min readDec 9, 2022

--

Laravel Eloquent ORM is an object-relational mapper (ORM) included with the Laravel PHP framework. It provides a simple and expressive way to interact with a database using an ActiveRecord-like implementation. This means that each Eloquent model corresponds to a table in the database, and each model’s attribute represents a column in that table. Eloquent makes it easy to work with and manipulate data in the database, allowing you to focus on building your Laravel application rather than writing complex SQL queries.

You can use Eloquent to perform common database operations such as retrieving data, inserting new records, updating existing records, and deleting records. It also provides powerful features like eager loading and relationships, which allow you to easily work with related data in your database.

Overall, Eloquent ORM is a powerful tool that can greatly simplify your database management and interaction within a Laravel application.

Useful Functions of Laravel Eloquent (ORM)

Some of the key functions and features of Eloquent include:

  1. Mapping each Eloquent model to a database table, and each model’s attribute to a column in that table.
  2. Performing common database operations such as inserting, updating, and deleting records.
  3. Eager loading and lazy loading, which allow you to efficiently retrieve related data from your database.
  4. Defining relationships between models, such as one-to-one, one-to-many, and many-to-many.
  5. Querying the database using a simple and intuitive syntax, which allows you to easily filter, sort, and paginate your data.
  6. Using events and observers to trigger actions before or after a model is created, updated, deleted, or saved.
  7. Using accessors and mutators to automatically format and manipulate model data when it is retrieved from or stored in the database.
  8. Customizing the behavior of a model by using traits, observers, and other advanced techniques.

Here are a few tips and tricks for using Laravel Eloquent ORM effectively:

Use the $guarded property on your models to specify which columns can be mass-assigned. This can help prevent accidentally exposing sensitive data in your database.

1 — In Laravel, the $appends attribute on a model allows you to specify additional attributes that should be included when the model is converted to an array or JSON. For example, you might have a User model with a posts relationship, and you want to include the number of posts a user has when the User model is converted to an array. You could do this by adding an appends attribute to the User model like this:

class User extends Model
{
protected $appends = ['post_count'];

public function posts()
{
return $this->hasMany(Post::class);
}

public function getPostCountAttribute()
{
return $this->posts->count();
}
}

In this example, the appends attribute tells Laravel that the post_count attribute should be included when the User model is converted to an array or JSON. The getPostCountAttribute method is used to define the value of the post_count attribute, which is the number of posts that the user has. When the User model is converted to an array or JSON, the post_count attribute will be included with the appropriate value.

2 — Use the $hidden property on your models to specify which columns should be hidden when the model is converted to an array or JSON. This can be useful for hiding sensitive data or columns that are not relevant to your application.

class User extends Model
{
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
'email_verified_at',
'verified',
'api_token',
'verification_token',
'admin',
'deleted_at',
'pivot',
];
}

3 — Use the $dates property on your models to specify which columns contain date/time values. This will automatically cast these columns to Carbon objects, which makes it easy to work with dates and times in your application. For example when using SoftDeletes, preferred use :

class Product extends Model
{
protected $dates = ['deleted_at'];
}

4 — Use the with method on your queries to eager load relationships. This can improve the performance of your application by reducing the number of database queries needed to load related data.

use App\Models\Book;

// instead of doing this:
$categories = Category::all();

foreach ($categories as $category) {
echo $category->products->name;
}

// do this
$categories = Category::with('products')->get();

foreach ($categories as $category) {
echo $category->products->name;
}

For this operation, only two queries will be executed — one query to retrieve all of the categories and one query to retrieve all of the products for all of the categories:

select * from categories

select * from products where id in (1, 2, 3, 4, 5, …)

5 — Use the withCount method to include a count of related records on a model. This can be useful for showing the number of related records on a model without actually loading the related records themselves. It helps us improve the performance of our application.

// in case we have many-to-many relationship between Category and Product model
public function index()
{
$categories = Category::with('products')->withCount('products')->get();
// ...
}
<!-- So Instead of using : -->
<td>{{ $category->products->count() }}<td>
<!-- we can use : -->
<td>{{ $category->products_count }}<td>

There is also function called: withExists, returned True/False.

public function index()
{
$categories = Category::with('products')->withExists('products')->get();
// ...
}
<td>{{ $category->products_exists ? 'yes' : 'no'  }}<td>

6 — Use the findOrFail method to retrieve a record or throw an exception if it doesn't exist. This can save you from having to write separate queries to check if a record exists and then handle the case where it doesn't.

Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, an Illuminate\Database\Eloquent\ModelNotFoundException will be thrown:

$product = Product::findOrFail(1);

$product = Product::where('quantity', '>', 3)->firstOrFail();

If the ModelNotFoundException is not caught, a 404 HTTP response is automatically sent back to the client:

use App\Models\Product;

Route::get('/api/products/{id}', function ($id) {
return Product::findOrFail($id);
});

7 — Use the firstOrCreate and firstOrNew methods to quickly retrieve a record or create a new one if it doesn't exist. This can save you from having to write separate queries to check if a record exists and then insert it if it doesn't.

// instead of :
$category = Category::where('name', $name)->first();
$newCategory = false;

if (!$category) {
$category = Category::create([
'name' => $name,
]);
$newCategory = true;
}
if ($newCategory) {
// ...
}

// we can use :
$category = Category::firstOrCreate([
'name' => $name,
]);
if ($category->wasRecentlyCreated) {
// ..
}

The first parameter to check if this column exists, and the second additional fields.

$product->categoires()->firstOrCreate([
'name' => 'Technologie',
], [
'user_id' => $user->id,
]);

the difference is that firstOrNewneeds save() method to inert the record.

$category = Category::firstOrNew([
'name' => request('name')
]);
$category->save();

8 — Use the updateOrCreate method to update an existing record or create a new one if it doesn't exist. This can save you from having to write separate queries to check if a record exists and then update it or insert it if it doesn't.

Those function are useful if you don’t want to get repeatable records.

$user->roles()->updateOrCreate([
'name' => 'Administrator',
]);

Bonus !

In Laravel, the $guard property on a model determines which authentication guard should be used when using Laravel's built-in authentication features. The authentication guard defines which user provider and password hasher should be used for the model. For example, you might have a User model that uses the default web guard, which is defined in the config/auth.php configuration file like this:

'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],

The guard value tells Laravel which authentication guard to use for the model, and the passwords value tells Laravel which password hasher to use for the model. You can define multiple guards in your application and specify which guard to use for each model. This allows you to use different user providers and password hashers for different models in your application.

Conclusion:

Overall, Laravel Eloquent ORM offers many powerful features and capabilities that can help you work with your data more efficiently and effectively. By taking advantage of these tips and tricks, you can improve the performance and usability of your Laravel application.

If you have any idea or do you have any preferred functions, let us know in the comments section below!

--

--