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
You can use try catch method to handle exceptions
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.