1

In my Laravel 7.6 app I use resource collection with creator retrieved and I want in some cases show not all creator fields, but only some of them. I have in my control:

$activeVotes = Vote
    ::getByStatus('A')
    ->where('votes.id', 1) 
    ->with('voteCategory')
    ->with('creator')
return (new VoteCollection($activeVotes));

In app/Http/Resources/VoteCollection.php I have :

<?php

namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;

class VoteCollection extends ResourceCollection
{
    public static $wrap = 'votes';

    public function toArray($request)
    {

        $this->collection->transform(function ($votes) {
            return new VoteResource($votes);
        });

        return parent::toArray($request);
    }
}

and in app/Http/Resources/VoteResource.php :

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class VoteResource extends JsonResource
{

    public static $wrap = 'votes';
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'creator' => $this->whenLoaded('creator'),
            ...

How to defined if I need to show only some fields of creator above ?

EDITED:

My app/User.php has :

<?php

namespace App;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

use DB;
...
class User extends Authenticatable implements MustVerifyEmail
{
    use Billable;
    use HasApiTokens, Notifiable;
    use funcsTrait;
    protected $table = 'users';
    protected $primaryKey = 'id';
    public $timestamps = false;

    protected $userAvatarPropsArray = [];
    protected $avatar_filename_max_length = 255;
    protected $full_photo_filename_max_length = 255;
    protected static $password_length = 8;

    protected $fillable = [ 'username', 'email', 'status', 'provider_name', 'template_id', 'provider_id', 'first_name', 'last_name', 'phone', 'website', 'password',
    'activated_at', 'avatar', 'full_photo', 'updated_at', 'verified' ];

    protected $hidden = [ 'password', 'remember_token'  ];
    ...

    public function votes()
    {
        return $this->hasMany('App\Vote', 'creator_id', 'id');
    }
    ...

and app/Vote.php :

<?php

namespace App;

use DB;
use App\MyAppModel;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use App\Http\Traits\funcsTrait;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Validation\Rule;

class Vote extends MyAppModel
{
    use funcsTrait;
    use Sluggable;
    use HasTags;

    protected $table = 'votes';
    protected $primaryKey = 'id';
    public $timestamps = false;

    protected $casts = [
        'meta_keywords' => 'array'
    ];

    protected $fillable = ['name', 'slug', 'description', 'creator_id', 'vote_category_id', 'is_quiz', 'status', 'image'];
    protected static $logAttributes = ['*'];
    ...
    public function creator(){
        return $this->belongsTo('App\User', 'creator_id','id');
    }

In Vote and user models there are referenced to other model. Otherwize

   ->with('creator')

does not work. Are there some options I missed?

Thanks!

1
  • 1
    This solution might do what you want, you could create a new resource for the creator and then call it inside your VoteResource Commented Apr 29, 2020 at 15:53

1 Answer 1

1

I think you have two options.

  1. Use hidden on your user model

By using hidden, see the Laravel docs, you specify which fields are shown in the JSON or Arrray representation of your model.

  1. Select the fields in your with statement
$activeVotes = Vote::getByStatus('A')->where('votes.id', 1) 
                                     ->with('voteCategory')
                                     ->with(['creator' => function ($query) {
                                         $query->select('id', 'first_name');
                                     }]);

return (new VoteCollection($activeVotes));

Your need to include the field id, as this is responsible to join these two.

Sign up to request clarification or add additional context in comments.

4 Comments

I try : $activeVotes = Vote ::getByStatus('A') ->with('voteCategory') ->with(['creator' => function ($query) { $query->select('first_name', 'last_name', 'website'); }]) ->get(); and resulting 'creator' is null
Can you show where your Vote model? How are votes and creator connected? Separate tables with foreign keys? Just edit your question ans insert the needed infos properly formatted.
Pls look at EDITED
You need to select the id field because that is the field that joins votes with users/creators. I updated my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.