Search code examples
laravellaravel-blade

Display all types of messages sent to View in Laravel


I return to the index Route after various actions in various controller methods in Laravel. In different methods, I send different messages such as "success", "error" and... to the index Route. The index Route directs me to a blade file. How can I receive and display any type of message sent by different methods with just one coding? Currently I send messages with "with". for example:

number 1 method(){
   //some Code
   return to_route('sms.index')->with('error - '.$resultText);
}
number 2 method(){
   //some Code
   return to_route('sms.index')->with('success','action is success');
}

But on the view side, I have to write a piece of code like the following for each one:

@if(session()->has('success'))
    <div class="alert alert-success">
        <span>{{session('success')}}</span>
    </div>
@endif

and

@if(session()->has('error'))
    <div class="alert alert-danger">
        <span>{{session('error')}}</span>
    </div>
@endif

Is it possible to combine all of these? Or at least did the job with less code?


Solution

  • how about something like:

    return to_route('sms.index')->with('flash-msg', ['type' => 'danger', 'message' => $resultText]);
    
    // layout.blade.php
    @if(session()->has('flash-msg'))
        @php $flash_msg = session('flash-msg'); @endphp
        <div class="alert alert-{{ $flash_msg['type'] ?? 'success' }}">
            <span>{{ $flash_msg['message'] }}</span>
        </div>
    @endif