Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AbdulBazith's avatar

How to use alert box in laravel controller?

Guys I am working with a project milkfarm. My problem is I need an alert box instead of success flash message in controller. How it is possible? My client is asking to give an alert box instead of success message because when I enter the whole data in the form and click insert it moves to controller store() function and adds the data in the DB. But sometimes I need to check few values in the controller (say for example balance_amount<given_amount, total_stock<sold_stock) after that only i can insert those values

If these problem occurs it should throw an alert message to user to enter the correct amount or stock. My client doesn’t need flash messages for these checking. For successful insert flash message is ok but for cheking alert messages is needed. Both are done in same function store().

So kindly anyone help to make my problem solve . suggest some ideas please

0 likes
8 replies
newbie360's avatar

depends on what the meaning of "alert message"

most browser is not allowed use javascript alert

and are you looking for return old('variable') if Validation fail ?

1 like
AbdulBazith's avatar

@newbie360

ya java script alert only. but how could i use it in controller.

Normally we use flash success message in controller but i need java script alert in controller. how it is possible?

1 like
AbdulBazith's avatar

Can any one help to use java script alert in controller . please

1 like
Groax's avatar

You can do this.

Controller:

return redirect()->route('...')->with('jsAlert', $message);

View:

@if(session()->has('jsAlert'))
    <script>
        alert({{ session()->get('jsAlert') }});
    </script>
@endif 
3 likes
AbdulBazith's avatar

@groax

i tried the above code as


 return redirect()->route('Vendor_details.index')->with('jsAlert', 'updated succesfully');

and this is my view



@if(Session::has('jsAlert'))

<script type="text/javascript" >
    alert({{ session()->get('jsAlert') }});
</script>

@endif

but not working any problem Kindly help

you have mentioned session() but we didn't use it in controller then how it works

1 like
AbdulBazith's avatar
AbdulBazith
OP
Best Answer
Level 5

Guys this worked

controller


return redirect()->back() ->with('alert', 'Updated!');

 <script>
    var msg = '{{Session::get('alert')}}';
    var exist = '{{Session::has('alert')}}';
    if(exist){
      alert(msg);
    }
  </script>

6 likes
ramonribeiro96's avatar

try this

<script>
    var config = <?php echo json_encode($config); ?>;
    alert(JSON.stringify(config))
</script>

i'm using laravel 7, works for me.

Please or to participate in this conversation.