Home > database >  Return Resource instead of Model using laravel with
Return Resource instead of Model using laravel with

Time:10-19

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('App\Models\Author', '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?

CodePudding user response:

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)
    ];

CodePudding user response:

You can use Select.

Post::with('author')->select('author.id')->get();
  • Related