1

I am working on some multi tenancy updates to a Laravel app but hitting an issue when trying to pass a specific team ID into a method on a model from within another method.

Example:

In Controller:

$waitTime = $booking->estimatedWaitTime($teamId);

In Booking model:

public function queueLength()
{
    $booking = $this->todaysBookings;

    foreach ($bookings as $booking) {
        // Calculate the length of all bookings
    }
}

public function todaysBookings()
{
    return $this->hasMany('App\UserBooking')->whereHas('booking', function ($q) {
        $q->where('team_id', 2);
    });
}

This correctly returns the bookings and allows me to loop through them in the queueLength method. However, I want to be able to pass the team_id into the todaysBooking method.

When instead calling todaysBookings as a method:

$booking = $this->todaysBookings();

It doesn't return anything for me to loop through.

Any ideas how to achieve what I want to do here?

1 Answer 1

1

You can pass the id as parameter and then get the results :

public function todaysBookings($team_id)
{
    return $this->hasMany('App\UserBooking')->whereHas('booking', function ($q) use($team_id) {
        $q->where('team_id', $team_id);
    });
}

In the call you can do as follow :

$some_teame_id = 2;
$booking = $this->todaysBookings($some_teame_id)->get();

Why ?

Because the relationships in laravel serve as powerful query builders (documentation) :

Eloquent relationships are defined as methods on your Eloquent model classes. Since, like Eloquent models themselves, relationships also serve as powerful query builders, defining relationships as methods provides powerful method chaining and querying capabilities.

Relationship Methods Vs. Dynamic Properties :

The call of the relationship as Methods is needed when you want to add some more conditions and filters like this :

$booking->todaysBookings()->where('active', 1)->get(); //just an example :)

And if you do not need to add additional constraints to an Eloquent relationship query, you may simply access the relationship as if it were a property, Laravel will add the get() for you :)

$booking->todaysBookings
Sign up to request clarification or add additional context in comments.

2 Comments

Interesting, when not calling it as a method what is happening differently? Is that 'executing' it so you don't need to call get on it? (Yours works btw, thanks!)
I will assume you did it twice ;)

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.