How to use SweetAlert messages for validation in Laravel 8

Viewed 2448

I'm using Laravel to develop my project, and I want to return a SweetAlert error message when the user DOES NOT MARK the Recaptcha. I coded this in LoginController.php:

use App\Providers\SweetAlertServiceProvider;

protected function validateLogin(Request $request)
{
    $request->validate([
        $this->username() => 'required|string',
        'password' => 'required|string',
        'g-recaptcha-response' => ['required' , new Recaptcha]
    ],[
        'g-recaptcha-response.required' => alert()
        ->error('Bad','Attempt')->persistent('Ok')
    ]);
}

Instead of showing an alert, it returns the following message.

Error Object of class UxWeb\SweetAlert\SweetAlertNotifier could not be converted to string

However, I have already added this line to config/app.php in the provider's section.

UxWeb\SweetAlert\SweetAlertServiceProvider::class

So what's going wrong here? What else should I have done to return this alert message?

1 Answers

You can use manual validation to return something other than a string :

$validator = Validator::make($request->all(), [
        'username' => 'required|unique:posts|max:255',
        'password' => 'required',
        'g-recaptcha-response' => ['required' , new Recaptcha]
    ]);

    if ($validator->fails()) {
        if($validator->errors()->has('g-recaptcha-response'))
            SweetAlert::error('please validate the captcha, thanks !')
        return redirect()
                    ->back()
                    ->withErrors($validator)
                    ->withInput();
    }

also make sure you have installed and included sweetalert in your code :

installation :

composer require uxweb/sweet-alert

in your controller :

use SweetAlert;

in your blade view :

<html lang="en">
    <head>
        <!-- Include this in your blade layout -->
        <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    </head>
    <body>
        @include('sweet::alert')
    </body>
</html>

references :

laravel docs (1)
uxweb/sweet-alert repo (2)

Related