MichalGrab
MichalGrab

Reputation: 57

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?

Upvotes: 0

Views: 10777

Answers (2)

Manjunath Karamudi
Manjunath Karamudi

Reputation: 100

Someone had already answered but sometimes when you want to send parameters in 'with' it's not showing the toasts/notifications so you can use an alternative to that at that situation by Using 'Session::flash' to display short messages.

I've attached links for Session::flash at first and then PHPFlasher - a PHP based project to flash messages in form of toasts,sweetalerts,notifications.

Example

Snippets-

1.

 Session::flash('info','your feedback would be helfull!');
 flash->success('your feedback has been successfully loaded!');

Links:

Session::flash Documentation

Laravel flasher Documentation

Upvotes: 1

W Kristianto
W Kristianto

Reputation: 9313

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.

Upvotes: 1

Related Questions