3

I have the following scope:

public function scopeLabel($query, $label)
{
    return $query->with(['label' => function ($q) use ($label) {
        $q->where('name', '=', $label)->get();
    }]);
}

Which I then use as follows:

$appointments = Appointment::latest('created_at')->label($label)->get();

The $label is fetched from a POST form and it matches the name field of my labels table.

The above query works when I call it directly from the controller, like so:

    Appointment::with(['label' => function ($q) use ($label) {
        $q->where('name', '=', $label)->get();
    }])->get();

This then returns all results from my Appointments table, where the appointments.label_id matches the labels.id in the Labels table. I hope you're still with me :)

But when I use the query in a scope, like the above, it doesn't work. It simply returns all results, and I cannot seem to figure out why this is. Any pointers?

Hardist
  • 2,098
  • 11
  • 49
  • 85
  • Yes, never mind this, my query isn't working either if I put it directly in the controller. I will probably have to use whereHas or something. I will figure it out and post an answer :) – Hardist Jan 27 '16 at 17:22

1 Answers1

1

Answered already once, similar issue I had, and I didn't learn anything from it, shame on me.

Laravel Search Relationship

        $appointment = App\Appointment::whereHas('label', function ($query) use ($label){
            $query->where('name', '=', $label);
        })
            ->with(['status' => function($query) use ($label){
                $query->where('name', '=', $label);
            }])->get();
Community
  • 1
  • 1
Hardist
  • 2,098
  • 11
  • 49
  • 85