'How to return OK or failure in Laravel API?

I am creating an API function that updates some values.

I would like to make it return "failure" message when inserting or updating fails

However, when SQL is wrong or the update has failed I get this error message in the browser:

Illuminate\Database\QueryException SQLSTATE[42S22]: Column not found: 1054 Unknown ~

public function save(Request $request)
{
    $user = Auth::user();

    try {
        if ($request->type == 'morning')
        {
            \DB::table('stacks')->updateOrInsert(
                ['id' => $user->id;],
                ['column' => 'test']
            );
        }
        return ['message' => 'success'];
    }
    catch (\Throwable $e) {
        \DB::rollback();
        \Log::error($e);
        throw $e;
    }
}


Solution 1:[1]

You need to return the response as JSON like below:

catch (\Exception $e) {
    return response()->json([
        'errors'  => $e->getMessage(),
        'status' => 'failure',
    ], 400);
}

Solution 2:[2]

if you are just want ok on successfully msg on execution of code and Failure msg on Failed just simply do like that

$result = \DB::table('stacks')->updateOrInsert(
            ['id' => $user->id;],
            ['column' => 'test']
            );
    if(!$result){

        return response()->json(['message' => 'failure']);
    }else{

        return response()->json(['message' => 'success']);
    }

Solution 3:[3]

public function save(Request $request)
{
    $user = Auth::user();

    try {
        if ($request->type == 'morning_meal') {
            \DB::table('stacks')->updateOrInsert(
                ['id' => $user->id],
                ['column' => 'test']
            );
        }
        return response()->json([
            'error' => false,
            'message' => 'Success message here'
        ]);
    } catch (\Throwable $e) {
        return response()->json([
            'error' => true,
            'message' => 'Error message here'
        ]);
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 msk
Solution 3 ket-c