Using Laravel 8, I have a model with belongsTo
relationship with another.
class Author extends Model
{}
And another one,
class Post extends Model
{
public function author()
{
return $this->belongsTo('AppModelsAuthor', 'author_id');
}
}
// Controller
Post::with('author');
By using with
I can retrieve the author based on Post. However, all attributes from author are retrieved. I don’t want to return all fields since an author may have a confidential info.
If I have multiple table to get with(['model1', 'model2'...])
, this returns all foreign table fields.
Is there a way like, with(new AuthorResource())
so I can put logic into the resource like restrictions to fields to be displayed?
2
Answers
You can use Select.
You can create a PostResource, add an author field in an array, and pass the author resource over there.