Data retrieval is a crucial aspect of web development. Laravel offers powerful tools and features to simplify this process. However, managing relationships and retrieving related data can sometimes be a challenging task. But, don’t worry, you are in the right place through this post. In the last tutorials, we already saw hasOne relation and hasMany Relationships in Laravel 10. In this article, we will explore the latestOfMany relationship introduced in Laravel 10. This provides an efficient and effortless way to retrieve the latest related models. With its simple implementation and numerous benefits, the latestOfMany relationship proves to be a game-changer in data retrieval. We will see its benefit and features as well along with the example.
Hence, let’s quickly recap what we are going to build in this post.
In the above result, we have the users list. Also, next to the user, we have the latest todo of the respective user. Here, I have used hasOne relation along with the latestOfMany function.
What is the latestOfMany Relationship?
Before diving into the details of the latestOfMany relationship, it’s essential to have a basic understanding of it.
The latestOfMany relationship is a new addition to Laravel 10. This is used with the hasOne relation in Laravel. The main aim of it is to simplify the retrieval of the latest related models. This relationship type is particularly useful when dealing with scenarios where we need to fetch the most recent data from a related table. By using the latestOfMany relationship, developers can effortlessly access the latest related models without having to write complex and time-consuming queries.
Benefits and Use Cases of the latestOfMany Relationship in Laravel
The latestOfMany relationship offers several advantages over traditional methods of data retrieval. One of the key benefits is the simplicity it brings to the codebase. Developers no longer need to manually write intricate queries to fetch the latest related models; instead, they can rely on Laravel’s latestOfMany relationship method to handle this automatically. This not only saves development time but also ensures cleaner and more maintainable code.
The latestOfMany relationship is ideal for various use cases, including content management systems, social media platforms, and e-commerce applications. For example, in a blogging application, where each post can have multiple comments. The latestOfMany relationship allows us to easily retrieve the latest comment for each post. This feature enhances the user experience and enables real-time updates without the need for complex query logic.
How to Create and Use belongsTo Relationship in Laravel 10
Prerequisites
For implementing the latestOfMany relationship in Laravel 10 you will require these configurations.
- PHP >=8.1
- Composer
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
I am assuming you are ready with the project setup, hence, I am skipping the installation of Laravel 10.
Step 1 – Create Models and Migrations in Laravel 10
We will require two models and migrations for establishing this relation between models. As we know, Laravel offers a default model and migration for Users. Therefore, we can go with this one as well. However, we need another model and migration.
So, I will be creating this for Todo.
php artisan make:model Todo -m
After having the model and migration let’s add the schema for the tables.
How to Implement Yajra Datatable with Server Side in Laravel 10
Step 2 – Add Schema and Fillable Data in Laravel 10
For adding schema, we can start with user migration itself. So, by default, we have the below schema. However, you can add more as per the requirements.
<?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 in the todo migration.
<?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');
}
};
Next, you will have to migrate these schemas for generating the tables.
php artisan migrate
The tables are ready now. Therefore, you will have to add fillable property in these both 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',
];
}
After that, you will have to do the same 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'
];
}
We are done with the models and migrations. Now, let’s work on the main part which is the relationship.
Form Handling Inside DataTable to Submit All Rows in Laravel 10
Step 3 – Define latestOfMany Relationship in Laravel 10
In order to define this relationship, navigate to the User model and add the below relation.
public function latestTodo() {
return $this->hasOne(Todo::class, 'user_id', 'id')->latestOfMany();
}
The latestOfMany relation will work with the hasOne relation in Laravel. So that it will fetch only the last record from the todos table.
So, using this way, you can fetch the latest record against this. After adding this relationship, the User model snippet will become like this.
<?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 latest todo
* @relationType: latestOfMany
* @return
*/
public function latestTodo() {
return $this->hasOne(Todo::class, 'user_id', 'id')->latestOfMany();
}
}
Now, in order to check this, you will require some data in the users table and also in the todos table as per the migrations and relation.
So, let’s take a look at the data which I have added through the factory and seeder.
Similarly, I have the data in the todos table. That means, every user has 3 todos records in the todos table.
Now, we have to fetch the latest data means the third entry of every user’s todo. Hence, let’s move to the controller part.
Step 4 – Create a Controller to Fetch Relation Data
You need a controller to fetch this data and render it into a view. Hence, in order to create a controller, you will have to hit the below command.
php artisan make:controller UserController
The above command will generate the controller. Thereafter navigate to the controller and add the below functionality.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Function : Fetch Users
* @param NA
* @return response
*/
public function index() {
$users = User::with('latestTodo')->get();
return view('users', compact('users'));
}
}
The functionality is added in the above controller. But, next, you will have to create a view and iterate the data inside it.
Step 5 – Create a View For Rendering latestOfMany Data
In order to render the data to a view, you will have to create it first. Hence, Inside the views folder, create a blade file named users.blade.php. After that, let’s add the below snippet for rendering the data which are coming from the controller.
<!doctype html>
<html lang="en">
<head>
<title>Latest of Many 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"> Latest of Many Relationship in Laravel 10 </h4>
<div class="table-responsive pt-1">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th width="5%">Id</th>
<th width="20%">Name</th>
<th>Latest Todo</th>
</tr>
</thead>
<tbody>
@forelse ($users as $user)
<tr>
<td>{{ $user->id }} </td>
<td>{{ $user->name }} </td>
<td>
<dt>
<p class="pb-0 mb-0">Todo Id : {{$user->latestTodo->id}}</p>
{{ $user->latestTodo->title ?? null }} </dt>
<dd> <span>- {{ $user->latestTodo->description ?? null }} </span></dd>
</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>
Lastly, you will have to add a route for this.
Step 6 – Add a Web Route in Laravel 10
For adding a web route, you will have to navigate to the web.php file. Thereafter, add the below route.
<?php
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
Route::get('users', [UserController::class, 'index']);
After adding the route, you can run the application to see the result.
As a result, you can see the user list with the latest todo for each users.
Performance Optimization Techniques for latestOfMany
To ensure optimal performance when utilizing the latestOfMany relationship. Therefore, the developers should follow certain optimization techniques.
These techniques include:
- Query optimization: Analyzing the query execution plan and optimizing the database. You can use the indexes as well so that it can improve the performance of the latestOfMany relationship.
- Caching strategies: You can Implement caching mechanisms, such as Laravel’s built-in cache system. Also third-party solutions like Redis. So, these can reduce the number of queries and enhance the overall response time.
Therefore, by implementing these performance optimization techniques, developers can enhance the efficiency and scalability of the latestOfMany relationship queries, providing a seamless user experience
Summary
In summary, the latestOfMany relationship in Laravel 10 simplifies data retrieval by providing an effortless way to retrieve the latest related models. It can be used with hasOne relation in Laravel. The latestOfMany relationship proves to be a valuable tool for developers working with Laravel. Therefore, by leveraging this relationship, developers can enhance the performance, maintainability, and user experience of their Laravel applications.
Leave a Reply