Eloquent ORM Model for Database in Laravel

What is Laravel eloquent ORM ?

Laravel includes Eloquent, an object-relational mapper (ORM) that makes it enjoyable to interact with your database. In addition to retrieving records from the database table, Eloquent models allow you to insert, update, and delete records from the table as well. The Eloquent ORM included with Laravel provides a simple Active Record implementation for working with your database. Each database table has a corresponding “Model” which is used to interact with that table. Before getting started, be sure to configure a database connection in config/database .

Why we use eloquent ORM ?

Eloquent is an ORM, which means can automatically handle the relationships of your models for you. You can retrieve related models without writing complex queries. You can even retrieve database information without any kind of database knowledge at all. while Object–relational mapping (ORM, O/RM, and O/R mapping tool) in computer science is a programming technique for converting data between incompatible type systems using object-oriented programming languages.

How we use ORM model for create and show columns in migration table ?

  • Firstly create a database if you want then customize it your project .env .
  • After that, create a migration table, Controller class and Model class by just a command:
php artisan make: model Employee -mc 
  • Then create a schema into migration table and migrate it:
  • After that you just open Controller class and import model class as “use App\Models\Employee” and create two anonymous class either firstOrCreate() or firstOrNew() into controller class as:
$employee = Employee :: firstOrCreate
(
   ['name' => "shubham"],
   ['email'=>"shubham@gmail.com",'city'=>"allahabad",'marks'=> "50"]  
);
  • While, in firstOrNew() you should be add save() for fetching and inserting a data:


$employee = Employee :: firstOrNew
(
   ['name' => "shubham"],
   ['email'=>"shubham@gmail.com",'city'=>"allahabad",'marks'=> "50"]  
);
  $employee -> save();
  • Before all this, you must be added fillable property into model class for assigning the data which is:
protected $fillable = ['name','email','city','salary'];