Laravel provides a powerful and expressive database ORM (Object-Relational Mapping) called Eloquent.
As well as a query builder for more direct SQL queries.
Laravel's migration system helps manage database schema.
1. Database Configuration:
- Laravel stores database connection details in the config/database.php file.
- You need to set up the database driver (e.g., MySQL, PostgreSQL), host, database name, username, and password here.
2. Create a Migration:
create a new model file using this command.
php artisan make:migration create_table_name
php artisan make:migration CreateUsersTable
// database/migrations/2022_01_01_000000_create_users_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
?>
3. Run Migrations:
For executing migration use this command
php artisan migrate
4. Database Seeding:
Database seeding allow you to populate your database with dummy data for testing or development purposes.
php artisan db:seed
5. Create a Model:
Models represent database tables and interact with them.
Create a model run this command
php artisan make:model ModelName
php artisan make:model Users
// app/Models/User.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// Eloquent will assume the "users" table by default
protected $table = 'custom_users';
}
?>
6. Define Model Relationships:
- Models can define relationships with other models, such as one-to-one, one-to-many, many-to-many.
- Use methods like hasOne(), hasMany(), belongsTo(), etc., to define relationships.
7. Eloquent:
- Eloquent provides a way to perform database operations.
- Use methods like create(), find(), where(), update(), delete(), etc.
8. Query Builder: (Use DB::)
The query builder is useful when you need more direct control over the SQL statements.
$users = DB::table('users')->where('name', 'abc')->get();
9. Raw SQL Queries:
If needed, you can execute raw SQL queries using Laravel's Query Builder or the DB facade.
$users = DB::select("SELECT * FROM users WHERE name = 'abc'");