Laravel is a popular PHP framework known for its elegant syntax and extensive features. One of the key aspects of Laravel is the ability to define relationships between database tables. The belongsTo relationship establishes a connection between two tables. Where one table belongs to another table. I am here with another informative post. Where we’ll dive into the complexities of Laravel 10. We will learn how to create and use belongsTo Relationship in Laravel 10. If you’re new to Laravel or want to brush up on your skills, you’ve come to the right place. In our last post, we learned how to implement hasMany Relationship in Laravel 10. In this post, we’ll cover everything from understanding the concept of a belongsTo relationship to implementing it in your Laravel 10 projects.
Before jumping directly to the coding stuff, let’s understand this relationship.
What is belongsTo Relationship in Laravel?
In Laravel, the belongsTo relationship is a fundamental concept to define and establish one-to-many relationships between database tables. It allows you to associate records from one table with records from another table based on a foreign key constraint. This can also be used as an inverse relation of hasOne and hasMany relation.
Before starting the example, let’s quickly take a look at the result that we will create in this post.
By using belongsTo relationship, I will fetch all the todos along with the author who created them. So, every todo will belong to at least one user.
So, let’s dive deep into this post for better understanding.
Prerequisites
We are going to implement the belongsTo relationship in Laravel 10. Hence, for running a Laravel 10 application, your system should match these configurations.
- PHP >=8.1
- Composer
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
Let’s have a project setup if you are done with the above configuration.
Step 1 – Project Setup For belongsTo Relationship in Laravel 10
You can create a project in Laravel 10 if don’t have one. I will be using Composer for handling this.
composer create-project --prefer-dist laravel/laravel laravel-relation
After the project setup, let’s make ready the Laravel project for database communication.
Step 2 – Database Configuration For Laravel 10
Firstly, you will have to create a database in MySQL. After that, navigate to the .env file and configure the Database details there.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_blog
DB_USERNAME={{ DATABASE_USERNAME }}
DB_PASSWORD={{ DATABASE_PASSWORD }}
After finishing this step, we will setup models and migrations for defining the belongsTo relationship in Laravel 10.
Step 3 – Create Models and Migrations For Defining the belongsTo Relationship
Regarding the model, we can use the default User model and migration. However, we will require to create one more model and migration. Hence, let’s do this quickly.
php artisan make:model Todo -m
The command will create a model named Todos and the migration for the todos table. I will establish the relationship between the user and the todo model.
After having the models and migrations, let’s add the schema and fillable data.
Step 4 – Create Schema and Add Fillable Data
By default in the users table migration, you will have some fields. You can add more as you required.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
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();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
}
};
After that, you will have to add the schema for the todos table.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('todos', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('todos');
}
};
Here, you are done with the migration. Now, let’s migrate these tables.
php artisan migrate
After that, you will have to add the fillable data to these models.
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
Similarly, you will have to add the fillable data for the Todo model.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Todo extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'title',
'description'
];
}
After creating the necessary database tables, we can move to the next step.
Step 5 – Define belongsTo Relationship in Laravel 10
We have two models named User and Todo. Hence, in order to define belongsTo relationship in Laravel there must be a hasMany or hasOne relation in the child model.
That means, if you are trying to establish a belongsTo relation from the User model to the Todo model then there should be a hasMany or hasOne relation in the Todo model first.
Let’s understand through the below snippet.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Todo extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'title',
'description'
];
/**
* Function : Relation for user
* @relationType : BelongsTo
*/
public function user() {
return $this->belongsTo(User::class, 'id', 'user_id');
}
}
In the above todo model, I have defined a relation for belongsTo. Actually, each todo will belong to any of the users from the users table.
Next, I will define a hasMany relationship in the User model. So that I can display todos and also the user who belongs to that Todo.
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
/**
* Function : Relation for Todos
* @relationType : hasMany
* @return HasMany
*/
public function todos() {
return $this->hasMany(Todo::class, 'user_id', 'id');
}
}
The relation is established between models. Now, you have to feed data in these both tables. I have filled up data in these tables using the factory classes and seeder. Therefore, I am skipping that step in this post.
Let me show you the database tables for the data.
Similarly, I have todo list with belonging user id.
So, based on these data, we can write a functionality to fetch these records.
Step 6 – Create a Controller to Fetch Relationship Data
In the next step, you will need a controller in order to fetch the data from the tables. Therefore, let’s create a controller for this.
php artisan make:controller TodoController
After having the controller, let’s put the below function in it.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Todo;
class TodoController extends Controller
{
/**
* Function : Fetch Todos
* @param NA
* @return response
*/
public function index() {
$todos = Todo::with('user')->get();
return view('todos', compact('todos'));
}
}
We have fetched the todos with user and returned to a view to display that. Hence, you will need a view in which you will render the data.
Step 7 – Create a View to Render Data
Navigate to views folder and create a blade file named todos.blade.php. After that add the below snippet in that.
<!doctype html>
<html lang="en">
<head>
<title>Belongs To Relationship in Laravel 10</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
<style>
.table {
vertical-align: middle;
}
</style>
</head>
<body>
<div class="container-fluid px-5 pt-3">
<h4 class="text-center fw-bold border-bottom pb-3"> Belongs To Relationship in Laravel 10 </h4>
<div class="table-responsive pt-1">
<h5 class="fw-bold ps-2"> Todo List </h5>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th width="5%">Id</th>
<th width="40%">Todo List</th>
<th>Description</th>
</tr>
</thead>
<tbody>
@forelse ($todos as $todo)
<tr>
<td>{{ $todo->id }} </td>
<td>
<dl>
<dt>{{ $todo->title }} </dt>
<dd> <span>- Author: {{ $todo->user->name }} </span></dd>
</dl>
</td>
<td>
{{ $todo->description}}
</td>
</tr>
@empty
<tr>
<td colspan="6">
<p class="text-danger">No data found </p>
</td>
</tr>
@endforelse
</tbody>
</table>
</div>
</div>
<!-- Bootstrap JavaScript Libraries -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"
integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.min.js"
integrity="sha384-7VPbUDkoPSGFnVtYi0QogXtr74QeVeeIs99Qfg5YCF+TidwNdjvaKZX19NZ/e6oz" crossorigin="anonymous">
</script>
</body>
</html>
That’s it for the functionality part. Now, we are good to go to run the application.
Wait, it is not finished yet. We missed something, yeah, that is route and without it we cannot run this.
So, let’s create a route for rendering the data.
Step 8 – Add a Web Route
For creating a route, navigate to the web.php file and add the below route.
<?php
use App\Http\Controllers\TodoController;
use Illuminate\Support\Facades\Route;
Route::get('todos', [TodoController::class, 'index']);
Yeah, that’s it. We have finished the functionality now, you can run and test the application.
Conclusion
In conclusion, the belongsTo relationship is a vital feature offered by Laravel for establishing one-to-many relationships between database tables. It enables seamless association of records between tables, providing flexibility and organization in your application’s data structure.
Leave a Reply