This post gives a bird's eye view of the options available in Laravel to work with Databases. Reading and storing data can be achieved by writing raw SQL queries.
A more Robust and Object-oriented approach is to use a query builder. "Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works perfectly with all of Laravel's supported database systems," - reads the description of Fluent Query builder on Laravel's official website.
Object Relational Mapping (ORM) - is a method that lets one query and manipulate data from a database using object-oriented principles. Conceptually, an ORM Library encapsulates the code required to manage data without using SQL directly. Laravel has Eloquent ORM as a part of its library. Eloquent ORM will allow database tables to have its own class to create, modify and delete table records.
Migrations is a class that manages database schema. The primary purpose of the Migration class is to provide easy version control while allowing the developer to modify records in the database without hassles.
Seeder is a tool that lets the developer add stub data into the database.
Step 1: Database Set up
Browse to the .env file in your laravel app and update the details of the following records:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Laravel_app
DB_USERNAME=root
DB_PASSWORD= $password
Step 2: Create a Model with a migration class
To create a model with a migration class, use the following command
php artisan make:model $FileName -m
This sets up a model and a migration class.
Step 3: Build database schema on the migration file. In my case, I am building a schema for a simple page data storage that includes a title, description and an image URL. and my code read this:
Schema::create('cms_data', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('description');
$table->string('imgUrl');
$table->timestamps();
});
Step 4: To migrate the database schema, use the following command
php artisan migrate
Now, you can see a new table with the schema in the database.