morphOne Last updated: 2022-10-01
There is no doubt that sometimes you need to use polymorphism
In your project and here we will explain how to bring one value through morphOne
Suppose a user can comment on some things using the Model name and user id
App\Models\User
Inside the comment table with morphs owner
(owner_type) , (owner_id)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model {
use HasFactory;
public function owner() {
return $this->morphTo();
}
}
And we needed in the user resource to retrieve his last comment
class User extends Authenticatable {
public function latestcomment() {
return $this->morphOne(Comment::class, 'owner')->orderBy('id', 'desc');
}
}
Note that we have prepared the method latestcomment
You will have to fetch the value inside the user resource this way
morphOne()->make('Latest Comment', 'latestcomment', Comments::class),
Label : Latest Comment
method: latestcomment
reference resource is : App\Dash\Resources\Comment