title | author | format | ||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Laravel Database and Models |
Vladimir Lelicanin - SAE Institute |
|
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.
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
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
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 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
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 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 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 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 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 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
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
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 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 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 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
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
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.