How do I get the last record in a table with a where clause using Laravel?

Ryan Sacks :

I'm creating database notifications. I have 2 Notification classes: InterviewRequestReceived.php:

$user = Auth::user();
        $interviewRequestReceived = InterviewRequestsReceived::latest()->where('user_id', $user->id)->get();
        return [
            'date_time1' => $interviewRequestReceived[$interviewRequestReceived->count() - 1]->latest()->get('date_time1'),
            'date_time2' => $interviewRequestReceived[$interviewRequestReceived->count() - 1]->latest()->get('date_time2')
        ];

and InterviewRequestSent.php:

public function toDatabase($notifiable)
    {
        $user = Auth::user();
        $interviewRequestSent = InterviewRequestsSent::latest()->where('user_id', $user->id)->get();
        return [
            'date_time1' => $interviewRequestSent[$interviewRequestSent->count() - 1]->latest()->get('date_time1'),
            'date_time2' => $interviewRequestSent[$interviewRequestSent->count() - 1]->latest()->get('date_time2')
        ];
    }

I have 3 tables. interview_requests_receiveds, interview_requests_sents and I created the notifications table and migrated. On my form I have 2 options for datetime fields, so Employers can choose 2 possible date and times that would work for them to interview a candidate. My form is working. My notifications are working except it's inserting all of the logged in Users' date and times, instead of just the last inserted record.

I'm trying to use latest(), but it's not working.

Sehdev :

As per Laravel Documentation

The latest and oldest methods allow you to easily order results by date. By default, result will be ordered by the created_at column. Or, you may pass the column name that you wish to sort by

If you want to use latest then instead of get() use first() function:

If there is already created_at column in your table then

$interviewRequestSent = InterviewRequestsSent::latest()->where('user_id', $user->id)->first();

OR

Assuming you want to get last record based on id column

 $interviewRequestSent = InterviewRequestsSent::latest('id')->where('user_id', $user->id)->first();

Or you can get the last record using any below methods

InterviewRequestsSent::where('user_id', $user->id)->last();

OR

InterviewRequestsSent::where('user_id', $user->id)->orderBy('id', 'desc')->first();`

Reference:

Laravel -> Query Builder -> latest method

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=297976&siteId=1