Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)
    ];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading