Laravel Eloquent Tutorial

Laravel Eloquent Tutorial

What is Laravel Eloquent?

Laravel Eloquent, an object-relational mapper (ORM) that uses an eloquent model and allows the interaction with a database. Each database table has its corresponding model that provides the interaction with a database.

Creating Laravel Eloquent Model (Class)

Let’s get started with creating a model class which is located at `app\Models` directory. You can use the artisan command to create the model as below:

php artisan make:model Tree

We can also create a migration for that model automatically using the artisan command:

php artisan make:model Tree –migration

This will generate the model with as below structure:

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Tree extends Model
{
   //
}

You can see the class Tree extends the Illuminate\Database\Eloquent\Model.

Configuring basic laravel eloquent modal properties

# Defining Table Name

After creating the model, we have not defined a database table that is to be used to interact with it. By default, the “snake case”, plural name of the class will be used as the table name unless another name is explicitly specified. So for now, eloquent will assume that the Tree model stores records in the trees table. 
If your model corresponding database table name is different then you may manually specify the model’s table name by defining a `table` property on the mode as below:

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Tree extends Model
{
   /**
    * The table associated with the model.
    *
    * @var string
    */
   protected $table = 'my_trees';
}

# Defining Primary Key

Now, eloquent assumes that each model’s corresponding table has a primary key named as id.  If our primary key is different then we can specify it using $primaryKey attribute.

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Tree extends Model
{
   /**
    * The primary key associated with the table.
    *
    * @var string
    */
   protected $primaryKey = 'tree_id';
}

In Eloquent, by default, the primary key is an auto-incremented integer value. If you want to provide a non-incrementing value to the primary key, then you have to set the $incrementing attribute to false.

protected $incrementing = false;

If your primary key is not an integer value, and if it’s a string value, then you can provide a different value to the $keyType attribute.

protected $keyType = 'string';

# Define Timestamps

In the eloquent model, there are by default created_at and updated_at columns corresponding to the DB table. Eloquent will automatically set these column’s values when models are created or updated. If you don’t want to use this column then you can set `$timestamps` property to false as below:

protected $timestamps = false;

If you want to format the model’s timestamps, you can use the $dateFormat property on the model. This format will be used for storing the timestamps in the database as well as when the model is serialized to an array OR JSON.

protected $dateFormat = 'U';

If you want to customize the names of the columns used to store the timestamps, you can define CREATED_AT and UPDATED_AT constants in the model:

const CREATED_AT = 'created_date';
const UPDATED_AT = 'updated_date';

# Defining DB Connection

In the model, there are by default DB connections that are configured in app/database.php. But if you want to use another connection that will be used when interacting with a particular model, you should define a $connection property in the model:

protected $connection = 'sqlite';

# Defining Default Attribute Values

By default, there’s no attribute value defined in the new model instance. But if you want to define default values for some model attributes, you can define it using $attributes property:

protected $attributes = [
	'db_column' => false,
];

Laravel Eloquent Operations

# Retrieving Data

Retrieving all data

We can use model’s all() method to retrieve all data as shown below:

use App\Models\Tree;
 
foreach (Tree::all() as $tree) {
   echo $tree->name;
}

Retrieving Single Models / Aggregators

If you don’t want to get all of the records and want only a single record, you can use one of the findfirst or firstWhere methods:

use App\Models\Tree;
 
// Retrieve a model by its primary key
$tree = Tree::find(1);
 
// Retrieve the first model matching the query constraints
$tree = Tree::where('tall', 1)->first();
 
// Alternative to retrieving the first model matching the query constraints
$tree = Tree::firstWhere('tall', 1);

And if you want to retrieve the first result of a query or perform some other action if no results are found. The firstOr method will return the first result matching the query or, if no results are found, execute the given closure:

$model = Tree::where('branch', '>', 3)->firstOr(function () {
   // ...
});

Not Found Exception

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

$tree = Tree::findOrFail(1);
 
$tree = Tree::where('branch', '>', 3)->firstOrFail();

Using condition to retrieve data

Instead of selecting all data or getting the first record, we generally want to retrieve specific records, at that time we can use conditions such as where, whereNot, whereIn, whereNotIn, and many more, details about all conditions is given below:

ConditionExplanationExample
whereInclude the data if all the given condition/s satisfied$model->where(‘id’, 1);
Return the record where the user’s id is 1
whereNotExclude the data if all the given condition/s satisfied$model->whereNot(‘id’, 1);
Return the record/s where the user’s id is not 1
whereInIncludes the data if the record satisfy with any of the given values$model->whereIn(‘id’, [1, 2, 3]);
Returns the records having any of the ids from 1,2,3
whereNotInExclude the data if the record satisfy with any of the given values$model->whereNotIn(‘id’, [1, 2, 3]);
Returns the records having not ids from 1,2,3
whereBetweenInclude the range of the data if all the given condition/s satisfied$model->whereBetween(‘id’, [1, 5])
Returns all the records having id between 1 and 5
whereNotBetweenExclude the range of the data if all the given condition/s satisfied$model->whereNotBetween(‘id’, [1, 5])
Returns all the records having not id between 1 and 5
whereNullInclude the data if the given field/s is null or empty$model->whereNull(‘name’);
Returns records having name null or empty

Retrieving Or Creating Models

Sometimes if we want to insert a record if it does not exist then laravel provides two different methods, one is firstOrCreate() and second is firstOrNew().

The difference between firstOrCreate() and firstOrNew() :

  • firstOrCreate() will automatically create a new entry in the database if there is no match found. Otherwise it will give you the matched item.
  • firstOrNew() will give you a new model instance to work with if no match was found, but will only be saved to the database when you explicitly do so (calling save() on the model). Otherwise it will give you the matched item.

Both methods check for all the arguments to be present before it finds a match. If not all arguments match, then a new instance of the model will be created.

If you only want to check on a specific field, then use firstOrCreate([‘field_name’ => ‘value’]) with only one item in the array. This will return the first item that matches, or create a new one if no matches are found.

You can see the example for different use case below:

use App\Models\Tree;
 
// Retrieve tree by name or create it if it doesn't exist
$tree = Tree::firstOrCreate([
   'name' => 'Oak'
]);
 
// Retrieve tree by name or create it with the name, branches, and leafs attributes
$tree = Tree::firstOrCreate(
   ['name' => 'Pine'],
   ['branches' => 10, 'leafs' => '1000']
);
 
// Retrieve tree by name or instantiate a new tree instance
$tree = Tree::firstOrNew([
   'name' => 'Elm'
]);
 
// Retrieve tree by name or instantiate with the name, branches, and leafs attributes
$tree = Tree::firstOrNew(
   ['name' => 'Dracaena'],
   ['branches' => 20, 'leafs' => '500']
);

# Inserting Records

To insert a new record into a database, you should create a new model instance and set an attribute on the model. Then, call the save method on the model instance.

<?php
 
namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;
use App\Models\Tree;
use Illuminate\Http\Request;
 
class TreeController extends Controller
{
   /**
    * Store a new tree in the database.
    *
    * @param  \Illuminate\Http\Request  $request
    * @return \Illuminate\Http\Response
    */
   public function store(Request $request)
   {
       // Validate the request...
 
       $tree = new Tree;
 
       $tree->name = $request->name;
 
       $tree->save();
   }
}

# Updating record

To update a record, first, you need to retrieve a record and then update it. The updated_at timestamps will automatically be updated, so there is no need to manually set its value.

To update a record we have to set attribute value on the model that we want to update and at last call save() method.

use App\Models\Tree;
 
$tree = Tree::find(1);
 
$tree->name = 'Oak';
 
$tree->save();

If we want to update more then one record at the same time then we can use update method as shown below:

$tree = new Tree();
$tree->where('tree_id', 1)
           ->update(['votes' => 1]);

Update method should be used with condition statement or all record available in table will be updated.

# Deleting record

To delete a model, you can use delete method on the model instance:

use App\Models\Tree;
 
$tree = Tree::find(1);
 
$tree->delete();

If you want to delete all of the model’s associated database records, you can use the truncate method. The truncate operation will reset any auto-incrementing IDs on the model’s associated table:

Tree::truncate();

Deleting Model using condition statement

Yes, you can also delete all records matching the condition. Suppose, we want to delete all Trees that have leafs greater than 500 then we can do it as:

$deleteTree = Tree::where('leafs', '>', '500')->delete();

Using delete method permanently removes the record from the database. Laravel also provides a way to soft delete the records.

Soft delete does not actually removes the record from the database but set’s the deleted_at column value and ignores that record when we retrieve it via model.

Visit our other post here to know more about soft deleting records.

0 0 votes
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments