get latest record against foreign key and check whether its specific column has value NULL or not

Viewed 219

Hi I am working on a project Laravel where I need to update record in database by fetching last(latest) record against foreign key, The scenario is fetch latest record(row) and if its specific column (amendments_to) has NULL value update it with some string else insert a new record. Below is my code what it does is always updates last row only no matter what the value in amendments_to column is.

OrderResponse::where('send_id', $id)
    ->orderBy('id', 'desc')
    ->take(1)
    ->update(['amendments_to' => $request->comment]);
1 Answers

If you only are doing it with a single row at a time, i would simply do a more Eloquent approach. Laravel has a helper for latest() query.

$orderResponse = OrderResponse::where('send_id', $id)
    ->latest()
    ->first();

if (!$orderResponse->amendments_to) {
    $orderResponse->amendments_to = $request->comment;
    $orderResponse->save();
} else {
    $newOrderResponse = new OrderResponse([
        'amendments_to' => $request->comment,
        'send_id' => $id,
        // other fields
    ]);
    $newOrderResponse->save();
}
Related