How to make alert with sweetalert2 in laravel

174 Views Asked by At

i want to make alert after add data with sweetalert2

my controller

public function store(StoreProductRequest $request)
    {
        $validated = $request->validated();

        if($request->file('image')){
            $validated['image'] = $request->file('image')->store('product-images');
        }

        Product::create($validated);
        
        return redirect('/dashboard/products')->with('success', 'Product has been added!');
    }

my index

@extends('dashboard.layouts.main')

@section('container')

<section class="section">
  @if (session()->has('success'))
    <script>   
          Swal2.fire({
              icon: "success",
              title: "Success",
          })
    </script>
  @endif   
   
//content

@endsection

my main

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard | {{ $tittle }}</title>
    
    <link rel="stylesheet" href="/assets/extensions/sweetalert2/sweetalert2.min.css">

    <link rel="stylesheet" href="/assets/extensions/simple-datatables/style.css">

    <link rel="stylesheet" href="/assets/compiled/css/table-datatable.css">
  
  <link rel="stylesheet" href="/assets/compiled/css/app.css">
  <link rel="stylesheet" href="/assets/compiled/css/app-dark.css">
  <link rel="stylesheet" href="/assets/compiled/css/iconly.css">
</head>

<body>
    <script src="assets/static/js/initTheme.js"></script>
    <div id="app">
        @include('dashboard.layouts.sidebar')
        <div id="main">
            @include('dashboard.layouts.header')
            <div class="page-heading">
                <div class="row justify-content-between align-items-center">
                    <div class="col-md-3">
                        <h3 class="my-auto">{{ $tittle }}</h3>
                    </div>
                    <div class="col-md-1 ">
                        <div class="dropdown">
                            <a class="d-flex align-items-center" role="button"
                                id="dropdownMenuButton" data-bs-toggle="dropdown" aria-haspopup="true"
                                aria-expanded="false">
                                <div class="avatar avatar-md">
                                    <img src="/assets/compiled/jpg/1.jpg" alt="Face 1">
                                </div>
                            </a>
                            <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                                <h6 class="dropdown-header text-muted">Action</h6>
                                <form action="/logout" method="post">
                                    @csrf
                                    <button class="dropdown-item" type="submit">Logout</button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
                
            </div>
            <div class="page-content"> 
                <section class="row">
                    
                        @yield('container')

                </section>
            </div>
            @include('dashboard.layouts.footer')
        </div>
    </div>
    <script src="/assets/static/js/components/dark.js"></script>
    <script src="/assets/extensions/perfect-scrollbar/perfect-scrollbar.min.js"></script>
    
    
    <script src="/assets/compiled/js/app.js"></script>
    

{{-- Sweet Alert --}}
<script src="/assets/extensions/sweetalert2/sweetalert2.min.js"></script>>
<script src="/assets/static/js/pages/sweetalert2.js"></script>>
    
<!-- Need: Apexcharts -->
{{-- Dashboard --}}
<script src="/assets/extensions/apexcharts/apexcharts.min.js"></script>
<script src="/assets/static/js/pages/dashboard.js"></script>

{{-- Datatable --}}
<script src="/assets/extensions/simple-datatables/umd/simple-datatables.js"></script>
<script src="/assets/static/js/pages/simple-datatables.js"></script>

</body>

</html>

sweetalert2.js

const Swal2 = Swal.mixin({
  customClass: {
    input: 'form-control'
  }
})

const Toast = Swal.mixin({
  toast: true,
  position: 'top-end',
  showConfirmButton: false,
  timer: 3000,
  timerProgressBar: true,
  didOpen: (toast) => {
    toast.addEventListener('mouseenter', Swal.stopTimer)
    toast.addEventListener('mouseleave', Swal.resumeTimer)
  }
})


document.getElementById("basic").addEventListener("click", (e) => {
  Swal2.fire("Any fool can use a computer?")
})
document.getElementById("footer").addEventListener("click", (e) => {
  Swal2.fire({
    icon: "error",
    title: "Oops...",
    text: "Something went wrong!",
    footer: "<a href>Why do I have this issue?</a>",
  })
})
document.getElementById("title").addEventListener("click", (e) => {
  Swal2.fire("The Internet?", "That thing is still around?", "question")
})
document.getElementById("success").addEventListener("click", (e) => {
  Swal2.fire({
    icon: "success",
    title: "Success",
  })
})
document.getElementById("error").addEventListener("click", (e) => {
  Swal2.fire({
    icon: "error",
    title: "Error",
  })
})

have an error sweetalert2.js:19 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at sweetalert2.js:19:33

I have tried debugging for @if (session()->has('success')) and got true.

I try not to use <script src="/assets/static/js/pages/sweetalert2.js"></script>>and just used Swal.fire inside the section, but still didn't show any results.

I have also tried to use Swal.fire on main before body but it doesn't work either, I don't think I understand the concept of using sweetalert correctly

I can only run sweetalert basic, nothing else 'document.getElementById("basic").addEventListener("click", (e) => { Swal2.fire("Any fool can use a computer?") })'

1

There are 1 best solutions below

5
Mohsin Ullah Shah On

Try this

@if (session('success'))
    <script>
        Swal.fire("{{ session('success') }}")
    </script>
@endif

Note: Make sure that you have included SweetAlert2 in your project

I have already did the same :

 @if (session('error'))
        <script>
            Swal2.fire("{{ session('error') }}");
        </script>
    @endif

it is working for me

Edit: if you want to add custem class check out this function :

function ErrorShow(Message) {
    Swal.fire({
        text: Message,
        confirmButtonText: 'Okey',
        customClass: {
        confirmButton: 'bluebtn', 
        }
    });
}

   

ErrorShow("{{ session('error') }}");