Sử dụng SweetAlert trong Laravel

1. Sweet alert là gì

Sweet alert là 1 gói trong Laravel , nó sử dụng để thay thế hộp thông báo của Javascript khi chúng ta sử dụng Laravel. Giao diện của nó khá đẹp, responsive và dễ dàng chỉnh sửa tùy theo sở thích người dùng.

2. Cài đặt Sweet alert trong Laravel

  • Để bắt đầu với SweetAlert2 , sử dụng Composer thêm package vào thư mục dự án:

        composer 

    require

    realrashid

    /

    sweet

    -

    alert
  • Sau khi cài đặt gói Sweet-alert , đăng ký gói trong Service Provider:

        

    RealRashid

    \

    SweetAlert

    \

    SweetAlertServiceProvider

    ::

    class

    ,

  • Trong file config/app.php của bạn :

  • Sau đó, ta thêm Alert facade vào biến aliases cũng trong file config/app.php :

'Alert'

=>

RealRashid

\

SweetAlert

\

Facades

\

Alert

::

class

,

3. Cấu hình

  • Thêm *’sweetalert::alert’*vào trong file giao diện của bạn :
    @

include

(

'sweetalert::alert'

)

  • Sau đó chạy lện dưới đây để sử dụng gói trong dự án :
php artisan sweetalert

:

publish
  • Nếu bạn không muốn sử dụng file sweetalert.all.js đã được load trước, bạn có thể sử dụng CDN(Content Delivery Network) :
@

include

(

'sweetalert::alert'

,

[

'cdn'

=>

"https://cdn.jsdelivr.net/npm/sweetalert2@9"

]

)

4. Demo thông báo với alert() và toast()

4.1. alert() demo

alert

(

)

->

success

(

'SuccessAlert'

,

'Lorem ipsum dolor sit amet.'

)

;

alert

(

)

->

info

(

'InfoAlert'

,

'Lorem ipsum dolor sit amet.'

)

;

alert

(

)

->

warning

(

'WarningAlert'

,

'Lorem ipsum dolor sit amet.'

)

;

alert

(

)

->

error

(

'ErrorAlert'

,

'Lorem ipsum dolor sit amet.'

)

;

alert

(

)

->

question

(

'QuestionAlert'

,

'Lorem ipsum dolor sit amet.'

)

;

alert

(

)

->

image

(

'Image Title!'

,

'Image Description'

,

'Image URL'

,

'Image Width'

,

'Image Height'

)

;

alert

(

)

->

html

(

'<i>HTML</i> <u>example</u>'

,

" You can use <b>bold text</b>, <a href='//github.com'>links</a> and other HTML tags "

,

'success'

)

;

4.1. toast() demo

Bạn có thể đặt vị trí hiển thị mặc định bằng cách sửa các biến trong file config/sweetalert.php hoặc sử dụng hàm helper position() , ngoài ra còn có thuộc tính đặt thời gian cho hộp thông báo tự đóng, hiển thị nút đóng hộp thông báo,… các bạn có thể tham khảo thêm tại link này tại mục Helpers.

toast

(

'Success Toast'

,

'success'

)

;

toast

(

'Info Toast'

,

'info'

)

;

toast

(

'Warning Toast'

,

'warning'

)

;

toast

(

'Question Toast'

,

'question'

)

;

toast

(

'Error Toast'

,

'error'

)

;

Trên đây mình đã giới thiệu cho mọi người về SweetAlert package trong Laravel, hẹn gặp mọi người trong các bài viết tiếp theo.

Tham khảo : https://realrashid.github.io/sweet-alert/