smzapp
smzapp

Reputation: 829

Return Resource instead of Model using laravel with

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?

Upvotes: 0

Views: 446

Answers (2)

Ashutosh Jha
Ashutosh Jha

Reputation: 154

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

Upvotes: 1

ABHILASHA K.M
ABHILASHA K.M

Reputation: 164

You can use Select.

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

Upvotes: 0

Related Questions