Laravel has one of many relationship tutorial

Hello friends, today in this tutorial we will see how to recover all the relevant records of a particular model. Previously, we discussed the one-to-many relationship between the two models but sometimes, we just want to retrieve a specific relative record of the relationship.

In the following example. The user model can have many post models and we want to retrieve the latest or popular post from a specific user.

Laravel offers a chic relationship that provides powerful query builders. In Laravel, chic relationships are defined in model classes. Laravel eloquent offers easy ways to build common relationships

It will be used in the version above Laravel 8.42, which is one of the many new relationships. One of many is a relationship that provides an easy way to recover the most recent or oldest model from a relationship. In this example tutorial, we have described how we can get the most recent post from a specific user model.

Step 1 : Create Migrations

We already have a user migration class, so all we need to do is create posts migration with the following command:

php artisan make:migration create_posts_table

go to database/migrations/ and edit post table migration.

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->integer('user_id')->unsigned();
        $table->string('title');
        $table->text('decription');
        $table->integer('views');
        $table->timestamps();

        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

go to database/migrations/ and edit users table migration.

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();
});

Run the migrate command to create tables into database.

php artisan migrate

Step 2 : Create Model

Now in this step we run the model command. In this command create model automatically, which is the following command.

php artisan make:model Post

We already have a user model, so add the following function to it

Get the latest post associated with the user.


public function latestPost()
{
    return $this->hasOne(Post::class)->latestOfMany();
}

Get the oldest post associated with the user


public function oldestPost()
{
    return $this->hasOne(Post::class)->oldestOfMany();
}

By default, the latestOfMany and oldestOfMany methods will retrieve the latest or oldest record. But, sometimes you may want to retrieve a specific record using different condition. For example you may want to retrieve the user's post with highest number of views. You can define it something like below:

Get the user's popular post.


public function popularPost()
{
    return $this->hasOne(Post::class)->ofMany('views', 'max');
}

Get the user's popular post using clousure function


public function popularPost()
{
    return $this->hasOne(Post::class)->ofMany(['views', 'max'], function($query) {
        $query->where('views', '<', '1000');
    });
}

Step 3 : Get Records:

Display a listing of the resource.

public function index()
{
    $post = User::find(1)->latestPost;

    dd($post);
}

Now if you want to retrieve the oldest post of the user, you can use the oldest post from the user model

public function index()
{
    $post = User::find(1)->oldestPost;

    dd($post);
}

Can retrieve the most viewed post.

public function index()
{
    $post = User::find(1)->popularPost;

    dd($post);
}

I hope this will help you to understand has one of many eloquent relationship in laravel app.

All Laravel relationship TUtorials

Laravel has one of many relationship tutorial