Skip to content

Latest commit

 

History

History
358 lines (249 loc) · 8.32 KB

laravel_database_and_models.md

File metadata and controls

358 lines (249 loc) · 8.32 KB
title author format
Laravel Database and Models
Vladimir Lelicanin - SAE Institute
revealjs
theme title-slide-attributes transition footer margin auto-animate preview-links link-external-newwindow scrollable embed-resources slide-level chalkboard multiplex slide-number incremental logo
default
data-background-image data-background-position data-background-repeat data-background-size
top left
no-repeat
100px
fade
Vladimir Lelicanin - SAE Institute Belgrade
0.2
true
auto
true
true
false
1
true
true
true
false

Introduction

Laravel is one of the top PHP frameworks with powerful database and model features. In this presentation, we will explore the Laravel database and models to enhance your understanding of this framework.


Eloquent ORM

Laravel uses the Eloquent ORM to interact with databases. With Eloquent, database tables are represented by models.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    // ...
}

Documentation: https://laravel.com/docs/8.x/eloquent


CRUD Operations

Eloquent provides easy ways to execute typical CRUD operations.

// Create
$user = new User;
$user->name = 'John Doe';
$user->email = '[email protected]';
$user->save();

// Read
$users = User::all();

// Update
$user = User::find(1);
$user->name = 'Jane Doe';
$user->save();

// Delete
$user = User::find(1);
$user->delete();

Documentation: https://laravel.com/docs/8.x/eloquent#basic-usage


Query Builder

Laravel's query builder provides an easy way to execute SQL queries without writing raw SQL.

DB::table('users')
    ->where('name', 'John')
    ->orWhere('name', 'Jane')
    ->get();

Documentation: https://laravel.com/docs/8.x/queries


Eager Loading

Eager loading is used to load relationships with the main model to reduce database queries.

$users = User::with('posts')->get();

Documentation: https://laravel.com/docs/8.x/eloquent-relationships#eager-loading


Relationships

Laravel provides various ways to define relationships between models. Here are some examples:

class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    public function role()
    {
        return $this->hasOne(Role::class);
    }

    public function permissions()
    {
        return $this->belongsToMany(Permission::class);
    }
}

Documentation: https://laravel.com/docs/8.x/eloquent-relationships


Polymorphic Relationships

Polymorphic relationships allow a model to belong to multiple other models on a single association.

class Comment extends Model
{
    public function commentable()
    {
        return $this->morphTo();
    }
}

class Post extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

class Video extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

Documentation: https://laravel.com/docs/8.x/eloquent-relationships#polymorphic-relationships


Scopes

Scopes are used to encapsulate commonly-used query constraints to reuse them in various parts of your application.

class User extends Model
{
    public function scopeActive($query)
    {
        return $query->where('active', true);
    }
}

$activeUsers = User::active()->get();

Documentation: https://laravel.com/docs/8.x/eloquent#query-scopes


Mutators

Mutators are used to set the value of a model attribute automatically.

class User extends Model
{
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }
}

Documentation: https://laravel.com/docs/8.x/eloquent-mutators


Accessors

Accessors are used to retrieve the value of a model attribute automatically.

class User extends Model
{
    public function getFullNameAttribute()
    {
        return $this->first_name . ' ' . $this->last_name;
    }
}

Documentation: https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor


Soft Deletes

Soft deletes allow you to delete records logically instead of physically. This helps to preserve data integrity while still being able to restore deleted records if needed.

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];
}

Documentation: https://laravel.com/docs/8.x/eloquent#soft-deleting


Model Factories

Laravel provides model factories to generate fake data for tests or seeders.

use App\Models\User;

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => bcrypt('password'),
    ];
});

$user = User::factory()->create();

Documentation: https://laravel.com/docs/8.x/seeding#using-factories


Database Migrations

Laravel provides database migrations to manage database schema changes in a version-controlled and team-friendly way.

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

Documentation: https://laravel.com/docs/8.x/migrations


Reverse Migrations

Reverse migrations allow you to revert a migration with a single command.

php artisan migrate:rollback

Documentation: https://laravel.com/docs/8.x/migrations#rolling-back-migrations


Database Seeding

Database seeding allows you to add test or demo data to your database.

use App\Models\User;

User::factory()->count(10)->create();

Documentation: https://laravel.com/docs/8.x/seeding


Database Transactions

Database transactions protect your data from inconsistencies by ensuring the atomicity of queries.

DB::transaction(function () {
    DB::table('users')->update(['votes' => 1]);

    DB::table('posts')->delete();
});

Documentation: https://laravel.com/docs/8.x/database#database-transactions


Query Logging

Laravel's query logging feature allows you to debug slow database queries in your application.

DB::enableQueryLog();

// Your queries here

$queries = DB::getQueryLog();

Documentation: https://laravel.com/docs/8.x/database#query-logging


Conclusion

In this presentation, we have explored some of the most powerful Laravel database and model features. Laravel makes it easy to perform CRUD operations, define relationships between models, and manage database schema changes.


References