Laravel Eloquent


What is Laravel Eloquent?

The PHP Laravel framework is packaged with the Eloquent Object Relational Mapper (ORM), which provides an extremely easy way to communicate with a database. As developers need to create complex websites and other applications, they prefer a hassle-free and shorter development time. Laravel helps make development faster and provides an adequate solution to most problems encountered. Varying business requirements are addressed with faster development, as well as well-organized, reusable, maintainable and scalable code. It works with custom web applications as it can cater to multiple databases and perform common database operations.

How does Eloquent work?

Developers can work in Eloquent with multiple databases efficiently using an ActiveMethod implementation. It is an architectural pattern where the model created in the Model-View-Controller (MVC) structure corresponds to a table in the database. The advantage is for models to perform common database operations without coding lengthy SQL queries. Models allow data querying in your tables, as well as inserting new records into tables. The process of synchronizing multiple databases running on different systems is simplified. There is no need to write SQL queries at all. All you have to do is to define database tables and relations between them, and Eloquent will do the rest of the job.

Laravel setup

To fully appreciate the utility of Eloquent ORM, understanding the ecosystem is a must. Here are the steps to get started:
  1. Install Laravel from getcomposer.org
  2. Create migrations using Artisan console
  3. Create Eloquent models
  4. Seed the database
Artisan Console is the name of the command-line interface packaged with Laravel. It provides a number of helpful commands to be used during the development of your application. It is driven by the powerful Symfony Console component.
To view a list of all available Artisan commands, you may use the list command:
php artisan list
All the commands come with a concise description of its arguments and options. This is shown in a “help” screen. To view a help screen, simply precede the name of the command with “help” as shown:
php artisan help migrate

Migration

Migration is a process of managing your database by writing PHP rather than SQL. Also it provides a way of adding version control to your database. Assuming that our database is up and running. To get started with migrations, you need to setup Laravel migration. Open the terminal and choose the correct path, and you can use artisan to create that migration table with this command:
php artisan migrate:install
To create a migration, just run the following command:
php artisan make:migration create_student_records
This creates the migration file. In your text editor, open the newly created file under the migration folder:
<?php
use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateStudentRecordsTable extends Migration
{
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
        Schema::create('student__records', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
    }

    /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
        Schema::dropIfExists('student__records');
    }
}
The code is a class with the same name ‘create student records’, and has two methods: up and down. The up method should make changes to the database; so whenever you migrate your database, whatever code is in the up method will be run. On the other hand, the down method should revert those changes to the database; so whenever you rollback your migration, the down method should undo what the up method did. Inside the up method is the schema builder that is used to create and manipulate tables. What will happen if you undo some of your migrations? All you have to do is to implement the following command:
php artisan migrate:rollback
And it will retract the last migration that was being implemented. Also, you can completely reset the database by running:
php artisan migrate:reset
This will undo all your migrations.

Defining Eloquent models

After you are done with the migration of your database, the next process is the seeding. Eloquent comes into the picture since seeding is inserting records into our database. Thus you will need to create your models before you can seed the database. Each database table has a corresponding model that is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table. The easiest way to create a model instance is using the following command:
php artisan make:model Student
An example of a Student model is shown below, which can be used to retrieve and store information from our students database table:
<?php
namespace App;
use IlluminateDatabaseEloquentModel;

class Student extends Model
{
    //
}
When you generate a model and at the same time you want to generate a database migration, you can either use the –migration or -m option:
php artisan make:model Student --migration

php artisan make:model Student -m

Seeders

Many get confused with seeders but it is simply a class that populates your database. The good thing with seeders is that they can be executed using a simple command to refresh your database. It helps in eradicating unreadable names such as “hjkahdkajshfkjsd” that may lead to overlooking some bugs.
The basic idea behind seeders is to help the problem of “dirty data” where one can develop a simple or even a powerful seeder. Overall seeders are a special set of classes that allow us to populate our database over and over with the same exact data. Let’s implement the following command:
php artisan make:seeder StudentsRecordSeeder
In the text editor, under the seeds folder, open the newly created file with filename: StudentsRecordSeeder.php. As you can see, this is just a very simple class with a single method called run().
<?php
use IlluminateDatabaseSeeder;

class StudentsRecordSeeder extends Seeder
{
    /**
    * Run the database seeds
    * @return void
    */

    public function run()
    {
        //
    }
}
The code is just a wrapper around a Console Command class, made specifically to help with the seeding task. Modify the code and then save it.
public function run()
{
    echo 'Seeding!';
}
And, will go back to the terminal:
php artisan db:seed --class=StudentsRecordSeeder
This is just purely calling the DB facade, but keep in mind that there’s no actual database interaction here. You can now populate the table with a few entries and run:
php artisan db:seed --class=class=StudentsRecordSeeder
Here you can keep deleting, adding, editing entries while you work, and then reset them with a simple command.

Post a Comment

0 Comments