skip to Main Content

I am adding a store method to a controller that will create and save a new model to the database using the following code:

public function store(Request $request)
{
    $validated = $request->validate([
       'name' => 'required|string',
       'description' => 'required|string',
    ]);

    $team = Book::create($validated);

    $request->session()->flash('flash_message', "Book created successfully.");

    return redirect("/site/books");
}

It was said that if the Book creation fails for any reason, there will be an exception generated which will prevent the flash() from occurring, therefor that line does not need to be wrapped in an if() statement to check if the Book was actually created (nor a try/catch block or database transaction). Is this accurate? Are there situation where the creation could fail without an error or exception, which would result in an inaccurate success message? If so, how do I prevent this?

2

Answers


  1. You can use try catch method to handle exceptions

    public function store(Request $request) {
    $validated = $request -> validate([
        'name' => 'required|string',
        'description' => 'required|string',
    ]);
    try {
        $team = Book:: create($validated);
    
        $request -> session() -> flash('flash_message', "Book created successfully.");
    
        return redirect("/site/books");
    } catch (Exception $e) {
        return back()->with('error', 'Failed to create book. Please try again. ' . $e->getMessage());
    }
    
    Login or Signup to reply.
  2. $team = Team::create($validated);
    

    Given that team was actually created (as a new class), $team will be that new object.

    Therefore, in the unlikely even that no exception was thrown, you still can use the identity of $team to confirm your expectations or requirements.

    E.g. you can make the message show some property of the new entry so that the message has more information and value for the user.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search