-1

Is there any mechanism that we can know that the data sent from app is successfully inserted to database, as in stored procedure, we use output parameter.

How can we be sure that the data is inserted into database and in case if the data insertion operation is failed, how to catch the error cause and display in a user friendly way?

// controller code
public function store(Request $request)
    {           
        $validatedInput = $request -> validate([
            'NBookName' => 'required|string|min:3|max:100',
            'NBookId' => 'required|string|min:2|max:10|unique:books,BookID',  // unique:table_name,column_name
            'NBookUnitPrice' => 'required|max:5|'
        ]);

        $book = new Book;
        $book -> BookName = $request->input('NBookName');
        $book -> BookID = $request->input('NBookId');
        $book -> BookUnitPrice = $request->input('NBookUnitPrice');
        $book->save();

        return view('pages.about');
    }
user4221591
  • 2,084
  • 7
  • 34
  • 68

3 Answers3

0

The Eloquent method save returns either true or false, thus checking the return of the save will let you know if the operation was successful.

You can alternatively use the method saveOrFail which will also return true / false, but may also give a Throwable

From the documentation: https://laravel.com/api/5.3/Illuminate/Database/Eloquent/Model.html#method_save

Examples:

if( $book->save() ){
    return response()->json($book, 200);
} else {
    return response()->json(['error' => 'Could not save'], 400);
}

or

try {
    $book->saveOrFail();
    return response()->json($book, 200);
} catch( \Exception $e ){
    return response()->json(['error' => $e->getMessage()], 400);
}
Ole Haugset
  • 3,709
  • 3
  • 23
  • 44
0

save() will return a boolean, saved or not saved. So you can either do Like:

$saved = $book->save();
if(!$saved)
{
    App::abort(500, 'Error');//Or return any message to view
}

For more details:check-if-laravel-model-got-saved-or-query-got-executed

Ammar Ali
  • 692
  • 6
  • 20
0

I'd start off by separating the layer, I don't like watching validations, Eloquent queries and view related output in the same place.

Before reading the answer below, take a look at

https://laravel.com/docs/5.6/validation#form-request-validation

I'd make middleware to authenticate and authorize users, then use formrequests to validate the input data, and by the time it reaches the controller, the user is authenticated, authorized, data validated and all it's needed is call someone that is responsible for the insert operation and return something to the UI.

"How can we be sure that the data is inserted into database and in case if the data insertion operation is failed"

Generally, a try catch will do:

public function store(Request $request)
    {            
        try {
            $validatedInput = $request -> validate([
                'NBookName' => 'required|string|min:3|max:100',
                'NBookId' => 'required|string|min:2|max:10|unique:books,BookID',  // unique:table_name,column_name
                'NBookUnitPrice' => 'required|max:5|'
            ]);

            $book = new Book;
            $book -> BookName = $request->input('NBookName');
            $book -> BookID = $request->input('NBookId');
            $book -> BookUnitPrice = $request->input('NBookUnitPrice');
            $book->save();
        } catch (\Exception $e) { 
         // return your pretty response
         // If the operation saving to the database fails, you'll get the information here on whatever it is about, 
         // as the generic exception catchs it. It should catch the stored procedure output aswell
        }
        return view('pages.about');
    }

If you plan on having a series of insertions and updates/deletes and you don't want them to break logic (insert some and stop at inserting when 1 is wrong), you can use DB; and use DB::beginTransaction(), DB::commit() and DB::rollback() on your code

https://laravel.com/docs/5.6/database

abr
  • 2,071
  • 22
  • 38