skip to Main Content

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


  1. You can use Select.

    Post::with('author')->select('author.id')->get();
    
    Login or Signup to reply.
  2. You can create a PostResource, add an author field in an array, and pass the author resource over there.

      return [
            'author' => AuthorResource::make($this->author)
        ];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search