Search code examples
laravelsweetalert

How to make alert with SweetAlert in Laravel


I would like to use SweetAlert to display my data.

I did my function

public function registration()
    {
        Gate::authorize('admin-level');
        $url = URL::signedRoute(
            'register',
            now()->addMinutes(20));

          return redirect('users')->with('success','$url');
    }

and route that goes with it

Route::get('registration', [App\Http\Controllers\UserController::class, 'registration'])->name('registration');

The problem is with message, since I downloaded SweetAlert with composer I should probably got everything working, but then when I try to execute my class with button threw the route:

<a href="{{route('registration')}}"><button type="button" class="btn btn-outline-primary">{{ __('Registration link') }}</button></a>
        @if(session('succes_message'))
        <div class= "alert alert-succes">
            {{session('succes_message')}}
        </div>
        @endif

Nothing pops up(when it should)

What might be wrong with it?


Solution

  • When you use ->with() it means, store items in the session for the next request.

    return redirect('users')->with('success', '$url');
    

    Here comes the question. What do you do after this?

    Create a notification information or an alert (popup with SweetAlert)?

    If it will be used as a notification, your code has no problem. If you want to make alert (popup with SweetAlert), your understanding is wrong.

    Just because the class you are using uses the name alert, doesn't mean it make an alert with SweetAlert.

    To use SweetAlert, you can add JavaScript in the header or before the </body> tag:

    <script>
    @if($message = session('succes_message'))
    swal("{{ $message }}");
    @endif
    </script>
    

    Or to use SweetAlert2 :

    <script>
    @if($message = session('succes_message'))
    Swal.fire(
      'Good job!',
      '{{ $message }}',
      'success'
    )
    @endif
    </script>
    

    If you are confused about placing the script in a specific blade view, please read my answer here.