Show the latest record from Polymorphic relationship in Laravel

Recently I came across a requirement where I had to show only the latest record from a polymorphic relationship. So basically I had a User model which has a polymorphic relation (morphMany) to the Comment model. Surprisingly it turned out pretty easy than I thought. So here is what I did:

Step 1: Create new function for latest record in User model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use App\Models\Comment;

class User extends Model
{
    public function comments(): MorphMany
    {
        return $this->morphMany( Comment::class, 'commentable' );
    }

    /**
     * Add this function to get the latest comment
     */
    public function latestComment()
    {
        return $this->comments()->take(1)->latest();
    }
}

Step 2: Load the parent records (in controller)

Controller is pretty simple, it just loads the records from User model.

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Fetch all users for listing
     *
     * @param Request $request
     * @return void
     */
    public function index( Request $request )
    {
        $users = User::all();

        return view( 'users.index', compact( 'users' ) );
    }
}

Step 3: Print the record (in blade template)

Now in the blade template for listing the users, we will access the latest comment as shown below:

// ./resources/views/users/index.blade.php

@foreach ($users as $user)
    ...
    @if ($user->latestComment->first())
        <p>
            {{ $user->latestComment->first()->text }}
        </p>
    @endif
    ...
@endforeach

Written by Arvind Bhardwaj

Arvind is a certified Magento 2 expert with more than 10 years of industry-wide experience.

Website: http://www.webspeaks.in/

Leave a Reply