Home > Net >  How to return ok or failure in Laravel API
How to return ok or failure in Laravel API

Time:12-22

I am creating an API function that updates some values.

I would like to make it return "failure" message. When inserting or updating is failed.

However When SQL is wrong or Update is failed.

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

a page in browser moves to the error page.

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

CodePudding user response:

You need to return the response as JSON like below:

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

CodePudding user response:

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']);
    }
  • Related