malhayek
2 years ago
398
11
Laravel

How to redirect the user back to the view with error when the controller return exception?

Posted 2 years ago by malhayek

In some unexpected cases my controller would return exception. Instead of showing the user error trace, I want to show them a user friendly error instead. (query timeout, duplicate record or something at the database level)

Here is my method

    public function store(AssetCategoryFormRequest $request)
    {
        $data = $request->getData();
        
        AssetCategory::create($data);

        return redirect()->route('asset_categories.assetcategory.index')
                                   ->with('success_message', 'Category was added!');
    }

I am guessing one way would be by using try/catch block

    public function store(AssetCategoryFormRequest $request)
    {
        try {
            $data = $request->getData();
            
            AssetCategory::create($data);
            return redirect()->route('asset_categories.assetcategory.index')
                                       ->with('success_message', 'Category was added!');

        } catch(QueryException $exception) {
            // But how to return to the same view and still pass an error message
            // I don't want to loose my request data also.
            Log::error($exception->getMessage());
            return back()->withInput()
                                  ->with('error_message','Unexpected error occurred while trying to process your request');

        }
    }

For some reason the above code still return stack trace instead of just the error message.

Is there a better way that using try/catch or is this the best way to go? How can I return the user back to the same view along with the request data and an error message?

Please sign in or create an account to participate in this conversation.