Introduction:
Laravel’s Eloquent ORM (Object-Relational Mapping) simplifies database interactions by allowing you to work with database tables using PHP objects. This beginner’s guide will walk you through the basics of Eloquent ORM in Laravel and demonstrate how to perform common database operations.
Getting Started:
To use Eloquent ORM, start by defining a model for each database table you want to interact with. Models in Laravel are PHP classes that extend the Illuminate\Database\Eloquent\Model
class.
Defining Models:
Let’s define models for both the user
and posts
tables:
User model code with Post model relation.
// app/Models/User.php namespace App\Models; use Illuminate\Database\Eloquent\Model; class User extends Model { // Model code here public function posts() { return $this->hasMany(Post::class); } }
Post model code with Users model relation.
// app/Models/Post.php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Post extends Model { // Model code here public function user() { return $this->belongsTo(User::class); } }
Migrations:
Next, let’s create migrations for the users
and posts
tables:
// database/migrations/2024_02_16_000000_create_users_table.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'); } }
Now add the user’s relation to the posts table using following code:
// database/migrations/2024_02_16_000001_create_posts_table.php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePostsTable extends Migration { public function up() { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('user_id'); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->string('title'); $table->text('content'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('posts'); } }
Controllers:
Now, let’s create controllers with resources to work with the users
and posts
models and their relations:
Creating the controllers with following commands:
php artisan make:controller UserController --resource php artisan make:controller PostController --resource
Let’s use the relation from user’s model for posts count.
// app/Http/Controllers/UserController.php namespace App\Http\Controllers; use App\Models\User; class UserController extends Controller { public function index() { $users = User::withCount('posts')->get(); return view('users.index', compact('users')); } // Other CRUD methods (show, create, store, edit, update, destroy) can be added here }
Now here is the code for posts controller which have the relation to the user, who created the respective post.
// app/Http/Controllers/PostController.php namespace App\Http\Controllers; use App\Models\Post; class PostController extends Controller { public function index() { $posts = Post::with('user')->get(); return view('posts.index', compact('posts')); } // Other CRUD methods (show, create, store, edit, update, destroy) can be added here }
Blade Templates:
Now, let’s update the Blade templates to fetch related data:
users/index.blade.php: having the post count for respective user.
<!-- resources/views/users/index.blade.php --> @extends('layouts.app') @section('content') <h1>Users</h1> <ul> @foreach ($users as $user) <li>{{ $user->name }} ({{ $user->posts_count }} posts)</li> @endforeach </ul> @endsection
posts/index.blade.php: having the user details who creates the respective post.
<!-- resources/views/posts/index.blade.php --> @extends('layouts.app') @section('content') <h1>Posts</h1> <ul> @foreach ($posts as $post) <li> <strong>Title:</strong> {{ $post->title }}<br> <strong>Content:</strong> {{ $post->content }}<br> <strong>Author:</strong> {{ $post->user->name }} </li> @endforeach </ul> @endsection
Conclusion:
Laravel’s Eloquent ORM provides a powerful and intuitive way to interact with databases in your web applications. With its expressive syntax and built-in features, you can efficiently perform database operations and manage relationships between database tables. By including controllers with resources and enhancing Blade templates to fetch related data, you can create RESTful APIs and handle CRUD operations seamlessly. As you delve deeper into Laravel development, mastering Eloquent ORM will become an invaluable skill.