Laravel Relationships Example is today’s main topic. In this tutorial, I will define two tables and establish the relationships between the tables. We will explore hasMany() relationship in this example from scratch. Eloquent Relationships are very compelling and save you lots of time. So let us get started this tutorial of Laravel Relationships Example.
Defining relationships in Laravel is something that every Laravel developer probably has done more than once.
But there are a lot of issues that you can run into when trying to implement a relationship.
Since there are different types of relationships, how do you know which one to pick? And how can you use the full potential of relationships when it comes to down to querying the models.
Laravel Relationships Example
Database tables are often related to one another. For example, a blog post may have many comments, or an order could be related to the user who placed it. Eloquent makes managing and working with these relationships efficiently and supports several different types of relationships.
- One To One
- One To Many
- Many To Many
- Has One Through
- Has Many Through
- One To One (Polymorphic)
- One To Many (Polymorphic)
- Many To Many (Polymorphic)
#Defining Relationships in Laravel
Eloquent relationships are defined as methods on your Eloquent model classes.
Since, like Eloquent models themselves, relationships also serve as robust query builders, defining relationships as methods provide powerful method chaining and querying capabilities.
For example, we may chain additional constraints on this posts relationship.
Now, let’s dive into the example.
Let us install Laravel.
Step 1: Install Laravel
I am using Laravel Valet.
laravel new relationships
If you are not using Laravel Valet, then install using the following command.
composer create-project laravel/laravel relationships --prefer-dist
After that, go into the project folder.
cd relationships
Setup the database in .env file.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=your database name DB_USERNAME=your username DB_PASSWORD=your password
Now, go to the terminal and migrate the two default tables using the following command.
php artisan migrate
Laravel Auth
Laravel provides us the Authentication Scaffold. So, let us use that. Type the following command.
php artisan make:auth
We need to create a user because we will save the user_id for the upcoming new table’s data.
Now, register the user by going to this URL: http://relationships.test/register. Of course, if you are not using Laravel Valet, then you need to start the Laravel development server by the following command.
php artisan serve
Go to this URL: http://localhost:8000/register.
Step 2: Create Category and Post models.
Now, we will create the following models.
- Category.php
Go to your terminal and type the following command.
php artisan make:model Category -m
It will also create the migrations. Now all the migration files are inside database >> migrations folder.
Now, write the schema for the create_categories_table.
// create_categories_table /** * Run the migrations. * * @return void */ public function up() { Schema::create('categories', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->string('title'); $table->timestamps(); }); }
Run the migrations using the following command.
php artisan migrate
Step 3: Create a category form.
Now, we do need an ID of a registered User. So first register in the Laravel application. You will redirect to the ‘/home’ route. The next step is to create a CategoryController. So, generate using the following command.
php artisan make:controller CategoryController
Next, go to the web.php file and create the route to add the categories.
// web.php Route::get('/category/create', 'CategoryController@create')->name('category.create');
Also, we need to define this route in the navigation bar. So inside views >> layouts >> app.blade.php file, add the right side the navigation link.
<li> <a class="nav-link" href="{{ route('category.create') }}"> Create Category </a> </li>
Inside CategoryController.php file, add the create() function.
// CategoryController.php public function create() { return view('category.create'); }
Inside views folder, create one folder called category and inside that folder, make one file called create.blade.php.
@extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header">Create Category</div> <form action="{{ route('category.store') }}" method="post"> <div class="card-body"> @csrf <label>Title</label> <input type="text" class="form-control" name="title" /> </div> <div class="card-footer"> <button type="submit" class="btn btn-primary">Add</button> </div> </form> </div> </div> </div> </div> @endsection
Now, define the store route inside a web.php file.
Route::post('category/store', 'CategoryController@store')->name('category.store');
But before, code the store function, we need to define the relationship between the Category and User model.
Step 4: Define User and Category Relationship.
Now, the One User can create multiple categories, and each Category belongs to a User.
So write the following function inside the User.php file.
// User.php public function categories() { return $this->hasMany(Category::class); }
Also, we need to define the inverse relationship inside the Category.php file.
// Category.php public function user() { return $this->belongsTo(User::class); }
Step 5: Save the categories in the database.
As we have defined the relationship between User and Category, we now can associate the Category with a particular User. We can write the following code inside the store() function.
// CategoryController.php public function store(Request $request) { $category = new Category; $category->title = $request->get('title'); $category->user()->associate($request->user()); $category->save(); return 'Success'; }
Now, we can save the data into the database.
The whole CategoryController.php file looks like this.
// CategoryController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Category; class CategoryController extends Controller { public function __construct() { $this->middleware('auth'); } public function create() { return view('category.create'); } public function store(Request $request) { $category = new Category; $category->title = $request->get('title'); $category->user()->associate($request->user()); $category->save(); return 'Success'; } }
Step 6: Display Categories with the User’s name.
Now, we need to display the posts with their username. Let us log out of the session and try to register with another user and create two-three categories as well. I have created the second user.
Now, create the categories with this second user.
From an Image, you can see that I have created three-three categories from two users.
Now, display the categories with respective users.
First, create a route to display the categories.
// web.php Route::get('categories', 'CategoryController@index')->name('category.index');
Code the index function inside the CategoryController.php file.
// CategoryController.php public function index() { $categories = Category::get(); return view('category.index', compact('categories')); }
Now, inside views,>> category folder, create one file called index.blade.php and write the following code inside it.
@extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> @foreach($categories as $category) <div class="card" style="width: 18rem;"> <div class="card-body"> <div class="card-title"><h3>{{ $category->title }}</h3></div> <div class="card-text"> Created By: <b>{{ $category->user->name }}</b><br /> Created At: {{ $category->created_at->diffForHumans() }} </div> </div> </div> @endforeach </div> </div> @endsection
Now, to display the user’s name, I have used Eager loading, which is an essential definition.
#Eager Loading in Laravel
At a basic level, Eloquent ORMs “lazy” load-related model data. After all, how’s the ORM supposed to know your intention? Perhaps you will never actually use the related model’s data after querying the model.
Not optimizing the query is known as an “N+1” issue. When you use objects to represent queries, you might be making queries without even knowing it.
Laravel’s ORM, called Eloquent, makes it trivial to eager load models, and even eagerly loading nested relationships. Eager loading optimizes the database queries related to ORM, in our case, it is Eloquent ORM.
So, the output will display like below image.
So, we have successfully use Laravel hasMany and Inverse relationships.
#Laravel one to one relationship
The one to one relationship is the most fundamental relationship that exists.
This type of relationship means that a model of type A may only be linked to one model of type B, and vice versa.
For example, a relationship between a User model and a Passport model would be a one to one relationship. A user can only have one passport, and a passport exclusively belongs to one user.
See the following code.
<?php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { public function passport() { return $this->hasOne(App\Passport::class); } }
In the User model, we create a method called a passport. We tell Laravel that the User model has one Passport by using the hasOne method.
In the Passport model, we define the inverse of the relationship. We let the Passport model know that it belongs to a User. We do this by using the belongsTo method.
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Passport extends Model { public function user() { return $this->belongsTo(App\User::class); } }
#Laravel one to many relationship
One to many relationship in Laravel means that one model of type A may be linked to multiple models of type B., But the model of type B belongs to only one model of type A.
For example, a relationship between a User model and an Order model would be a one to many relationship.
A user can have multiple orders, but the order only belongs to one user. See in the code.
<?php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { public function orders() { return $this->hasMany(App\Order::class); } }
Now, All we have to do now is let the Order model know that it belongs to a User model.
Let’s define the inverse of the one to many relationship.
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Order extends Model { public function user() { return $this->belongsTo(App\User::class); } }
#Laravel many to many relationship
Laravel many to many relationships means that one model of type A may be linked to multiple models of type B, and vice versa.
For example, a relationship between an Order model and a Product model would be a many to many relationship.
An order can have multiple products, and a product can be on multiple orders. Let’s see in code.
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Order extends Model { public function products() { return $this->belongsToMany(App\Product::class); } }
And you can define an inverse of this relationship like this.
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Product extends Model { public function orders() { return $this->belongsToMany(App\Order::class); } }
Many to many relationships are slightly more difficult to implement because they require a junction table in the database.
You can create this junction table in Laravel by creating a migration file.
We will see other relationships later in this blog. I have also put some links at the end of this post.
#Querying relationships
Querying a relationship is pretty straightforward. Since we defined the one to one relationship for the passport and the one to many relationships for the order, we can use them on the User model.
On every instance of the User model, we can now get the related passport and orders.
See the following code.
<?php $user = \App\User::find(1); // Query the passport relationship $user->passport->expiration_date; // Query the order relationship foreach($user->orders as $order) { $order->order_amount; }
Querying a many to many relationship works in the same way as the other relationships.
Also, the many to many relationship has a pivot attribute. This attribute represents the junction table and may be used like any other model.
Conclusion
You can refer to the eloquent relationships on Laravel’s official documentation.
Finally, our Laravel Relationships Example is over.
Recommended Posts
Laravel Eloquent Relationships
Laravel One To One Eloquent Relationships
Laravel One To Many Relationship
Laravel Many To Many Relationship
How about edit and delete
Man, I have been Watching videos, but your explanations have been so straight to the point. I do appreciate you Krunal
How to acces index.blade.php , please
i still confuse ’bout edit