1

I am currently using Laravel Excel to build a sheet. The sheet requires a query that returns a collection and I need the result of that collection to query a whereBetween() to get that collection for map().

I do have the ability to gather all submissions but I need to specify strictly from the user's model so the relations work properly and are limited to what is assigned to that user.

The current method I use in another area of code uses the following method:

$user_contracts = \Auth::user()->contracts()->get();
$submission_id = array();
foreach ($user_contracts as $contract) {
    $submissions = $contract->submissions()->get();
    foreach ($submissions as $submission) {
        $submission_id[] = $submission->id;
    }
}

$user_submissions = FormSubmission::whereIn('id', $submission_id)->get();

That returns the proper results.

This query() function is what I believe I am required to use to generate the map() function that is required by Laravel Excel to generate the sheet.

    public function query()
    {
        $time_start = Carbon::now()->setTime(0, 0, 0);
        $time_end = Carbon::now()->setTime(24, 0, 0);
        return User::query()->find($this->user->id)->contracts()->submissions()->whereBetween('created_at', [$time_start, $time_end]);
    }

Error Result: Property [submissions] does not exist on this collection instance.

Blood
  • 11
  • 1

1 Answers1

0

Thanks to Laravel Eloquent nested query I was able to answer my own question, sort of.

This is the final code I ended up with.

    public function query()
    {
        $time_start = Carbon::now()->setTime(0, 0, 0);
        $time_end = Carbon::now()->setTime(24, 0, 0);
        $contracts = $this->user->contracts()->get()->pluck('id')->toArray();

        return FormSubmission::query()->whereHas('contracts', function($q) use ($contracts) {
            $q->whereIn('contract_id', $contracts);
        })->whereBetween('created_at', [$time_start, $time_end]);
    }

I am still open to more elegant answers.

Blood
  • 11
  • 1