Updated July 5, 2023
What are the Laravel Models?
The Model corresponds to the letter ‘M’ in the MVC framework. The motive of Models in any Model view controller framework web application is to manage business logic. A Model is nothing but a class in the Laravel framework. This class is responsible to interact with underlying database tables. Laravel with Eloquent ORM is capable of handling the database more efficiently. ORM stands for ‘Object Relational Mapper’ and it is responsible for your swift interaction with the database. These Models provide you with an easy way to update, insert or retrieve data from the tables.
Firstly, we need to make a connection to the database using ‘config/database.php’. Now we will delve into Laravel Model creation as follows.
Defining Eloquent Models
Let’s see how to create a model. We will tell you the simplest way of model instance creation using Artisan command. You simply need to write make:model command whose syntax goes like this:
Syntax:
php artisan make:model <Model-Name>
Let’s take a simple example of the Model as follows:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Teacher extends Model
{
//
}
This Model will be used by us to store as well as retrieve information from the Teachers database.
Here, it may be noted that Eloquent automatically assumes that the records are stored in the ‘Teachers’ table as evidently the plural form of class is taken as the table name until and unless you specify it explicitly.
If you want to specify it explicitly, it can be done as follows:
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class Teacher extends Model
{
/**
* table to store teachers records.
*/
protected $table = 'my_teachers';
}
If you wish to generate model and database migration at the same time, this can be done by using either of –m or – migration option.
php artisan make:model Teacher --m
php artisan make:model Teacher -migration
By convention, column ‘id’ is the primary key of every table. Similar to specifying the table name explicitly, we can also specify the primary key as follows:
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class Teacher extends Model
{
/**
* Primary key.
*/
protected $primaryKey = 'teacher_id';
}
By default, the primary key is always assumed as an ‘int’ value which is always incrementing. Incrementing and type property can also be customized by setting the ‘incrementing’ property and ‘keyType’ property respectively as follows:
<?php
class Teacher extends Model
{
/*
* Defines incrementing or non-incrementing.
*
* @var bool
*/
public $incrementing = false;
protected $keyType = 'string';
}
Now let’s see how we can perform various operations on our database as ahead.
Eloquent and CRUD Operations
Eloquent ORM constitutes of CRUD operations which makes it simpler for users to interact with various databases. Various database operations and mapping of tables to object models are performed with it. All the interactions with the database which are required to perform CRUD operations are handled by it.
Let’s understand all of these operations one by one as ahead.
1. Creation of Records
Steps to create a new record in your database:
- Model instance creation
- Setting attributes
- Call ‘save’ function
<?php
namespace App\Http\Controllers;
use App\Teacher;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class TeacherController extends Controller
{
/**
* teacher instance creation
**/
public function storage(Request $request)
{
$teacher = new Teacher;
$teacher->name = $request->name;
$teacher->save();
}
}
2. Retrieval of Records
As discussed earlier, finding or retrieving information from the database is fairly easy with the help of Eloquent ORM. You can simply query your database and get the needed records.
Various methods can be used to retrieve data some of which are as below:
get()
If you want a number of records, then get() method can be used. It will get you an array of results as an output.
Example:
$rankTeachers = Teacher::where('teacher_rank', '<', 4)->get();
This code will get you the array of teachers with a rank of less than 4.
first()
Unlike the get() method, this method will produce only one result as an output.
Example:
$CarolDuff = Teachers::where('name', '=', 'Carol Duff')->first();
This code will find a specific teacher depending on the attributes provided.
all()
This method will yield all the records of a table.
Example:
$teacher = Teachers::all();
This code will yield all the teachers records.
find()
find() method returns all the matching records depending upon the parameter passed in query/code.
Example:
$teacher = Teachers::find(2);
This code will yield a specific teacher’s record by id.
3. Updation of Records
Steps to update a record in your database:
- Find and retrieve the record
- Set attributes
- Call save() method
Updating records is as easy as other operations discussed above. You just have to retrieve the record to be updated, set the desired attributes and call save() method.
Let’s understand this with an example as follows:
$CarolDuff=Teachers::where('name', '=','Carol Duff')->first();
$CarolDuff->rank_level = 4;
$CarolDuff->save();
This code will change the teacher rank level of Carol Duff to 4. Here first we have found and retrieved the particular teacher’s record which was needed to be updated. Secondly, we have set the desired attributes and then save() method is called.
4. Deletion of Records
Steps to delete a record:
- Retrieve record to be deleted
- Call delete() method
OR
- Call destroy() method
Deleting is as simple as other database operations. Firstly you have to find the record to be deleted, pull out the record and then call delete() method.
Example:
$teacher = Teachers::find(2);
$teacher ->delete();
Or you can simply call destroy() method as shown below:
- To delete one record:
Teachers::destroy(2);
- To delete multiple records:
Teachers::destroy(2, 3, 4);
Here it is to be noted that you can pass any column of a database table in delete() method whereas only the primary key column can be passed in destroy() method.
Conclusion – Laravel Models
Laravel, when it includes Eloquent ORM, becomes a powerful and robust framework that provides you with a competitive edge. It can be used very efficiently in order to manage and handle database and its interactions for your web application development. It lets you interact with different tables in your database using simple queries.
Recommended Articles
This is a guide to Laravel Models. Here we discuss the eloquent models along with eloquent and crud operations with examples. You may also look at the following articles to learn more –