search

Home  >  Q&A  >  body text

Queries that return a Laravel resource keep returning a 500 error.

<p>I'm trying to build an array of details to pass to a dashboard resource, but I'm having some issues trying to pass the data to the resource. <br /><br />In my controller I am building the query like this: <br /></p> <pre class="lang-php prettyprint-override"><code>$user = auth()->user(); $teams = Team::query() ->where('user_id', $user->id) ->get(); $jobs = Job::query() ->where('user_id', $user->id) ->get(); return new DashboardResource($user, $jobs, $teams); </code></pre> <p>Then go to the resource</p> <pre class="lang-php prettyprint-override"><code>public function toArray(Request $request): array { return [ 'name' => $user->name, 'teams' => TeamResource::collection($this->teams), 'jobs' => JobResource::collection($this->jobs), ]; } </code></pre> <p>I have been encountering a problem, that is;</p> <pre class="brush:php;toolbar:false;">Property [jobs] does not exist on this collection instance.</pre> <p>I think I may have done something wrong. </p>
P粉293341969P粉293341969489 days ago439

reply all(1)I'll reply

  • P粉497463473

    P粉4974634732023-07-28 00:32:15

    The JsonResource constructor only accepts one parameter. You should create an association between Teams and Jobs in the user model, and then call $user->teams and $user->jobs in the resource.

    reply
    0
  • Cancelreply