danimohamadnejad's avatar

best way to add messages to a request?

hello. In my ecommerce application I want the users to be able to add coupon codes and get some discount. I am using a form for recieving coupon code from user in form of a POST request. if every thing is okay and coupon code exists user may get discount but there are situations in which coupon code may not exist or use has already used it or it has reache maximum usage count or user cart order total can not meet minimum amount to allow him for using coupon. as you see there may be multiple messages that I may want to return to user to be displayed. what is a good reusable way or a design pattern which can help me add these messages to each other without using lots of If and else if statements? thank you in advance

0 likes
3 replies
jove's avatar

I use https://github.com/spatie/laravel-flash Then I have a notification component and a info alert component made from the notification component that I simply display when I flash a info message and return back.

I currently use this views/shared/flash.blade.php

@if (flash()->message)
    @component('components.alert', ['class' => flash()->class])
        {{ flash()->message }}
    @endcomponent
@endif

views/components/alert.blade.php

<!-- Alert component -->
<div class="alert alert-{{ $class }}">
    {{ $slot }}
</div>
<!-- End Alert component -->

then I include this on all pages that should have this, could probably done it in a layout and extended from it if you use it a lot.

@section('content')
    @include('shared.flash')
    @include('shared.error')
    ...

then in etc a store request

flash('Agent created', 'success');
return redirect()->route('agents.index');
1 like
mware's avatar

@danimohamadnejad I use this package for toast messages: https://github.com/yoeunes/toastr

I has worked very well for me and is super easy to setup. Once you install the package all you have to do is add these directives in you main layout file(s): @toastr_css @toast_js @toast_render. The css directive goes in the header, the js and render should be place right before the closing body tag.

To add a message you simply use:


toastr('Whatever your success message is')

In your controller and you will get a toast message rendered when the view is loaded. You can read the docs for other styles. Good luck!

2 likes
Snapey's avatar

If you have multiple conditions to test, then unfortunately, a lot of if statements are going to be required.

1 like

Please or to participate in this conversation.