1

I have set up a relationship between 2 models Route and Booking

a Route has many bookings a Booking belongs too a route

Route Model:

//
public function books()
{
    return $this->hasMany(Booking::class);
}

Booking Model

public function route()
{
    return $this->belongsTo(Route::class);
}

Now in my controller i try to access the route a particular booking belongs to

public function bookFeed(Request $request, Booking $booking)
{
    $bookR = $booking->with('route')->get();

    dd($bookR);
}

or even this

$bookR = $bookRef->route()->get();

dd($bookR);

and i get a collection with multiple Route arrays, now to access a value i have to do

$bookR[0]->value

why is this so, what am i doing wrong?

3
  • what is the result of dd($booking->exists); Commented Apr 11, 2018 at 10:34
  • the result is true Commented Apr 11, 2018 at 10:36
  • 1
    Try $booking->load('route'); instead of $booking->with('route')->get() This will load the related route of your booking. Your code starts a new query when using like this. Commented Apr 11, 2018 at 10:39

2 Answers 2

2

Use first() in your query

$bookR = $booking->route()->first();

or

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

4 Comments

you were using ->get() which generates collection
what if i wanted to use say the id of the retrieved route to query the bookings table again, will i write another query or there's an efficient way to do this?
If you check your query logs, this solution executes multiple select queries in database. However this is unnecessary. You already have the booking object. The only thing you need to do is to load the relation instead of querying the booking itself.
@dapo you already have booking object, you don't need to bother again
1

Try this:

public function bookFeed(Request $request, Booking $booking)
{
    $booking->load('route');

    dd($booking); // or $booking->route now.
}

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.