Laravel 5 Eloquent getting records from related tables

I'm new to laravel and I'm using Laravel 5.2 I want to have the record of the maximum end date in a bookings columns of a perticular request. My tables are like :

request
-----------
id | name
----------
1   | My request

bookings
-----------
id | request_id | start_date | end_date
--------------------------------------------
1   | 1         | 2016-03-01 | 2016-03-05
2   | 1         | 2016-03-10 | 2016-03-20
3   | 1         | 2016-03-25 | 2016-03-28

Request Model
------------------
public function bookings()
{
    return $this->hasMany( 'App\Booking' );
}

I want to have the request data with the maximum end date ( for the example above the record will be booking Id : 3 ). Please help.

I've tried the following :

$request = \DB::table( 'requests' )
                ->join( 'bookings', 'requests.id', '=', 'bookings.request_id' )
                ->where( 'requests.id', 1 )
                ->max( 'bookings.end_date' );

But I wonder how to do this with eloquent.

Answers


You can desc-order by that date and pick the first record:

$request = Request::find(1)->bookings()->orderBy('end_date', 'DESC')->first();


Need Your Help

Make a "hotkey" to focus a TextBox in WPF

.net wpf hotkeys

I am trying to make a hot key (ie Ctrl + Y) that will change the focus to a text box.

How to import DDMathParser in iOS 8 project?

swift ios8 xcode6.3.1

I am totally new to swift and developing my first application for iOS. I need to use DDMathParser with it. I followed guide at their site but i am getting errors at import statement