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?

1
  • 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 :) Commented Jan 27, 2016 at 17:22

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

Comments

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.