search

Home  >  Q&A  >  body text

Laravel controller cannot return session variables

<p>I'm learning Laravel and I'm trying to put a success message into the session and show it in the view but it doesn't seem to work</p> <p>This is my code in the view section</p> <pre class="brush:php;toolbar:false;"><div class="col-sm-12 col-xl-12"> @if (session()->has('msg')) <h5> {{ session('msg') }}</h5> @endif</pre> <p>This is the controller function I use to add new content and put messages into the session</p> <pre class="brush:php;toolbar:false;">public function store(CatalogRequest $request) { $status=$this->catalog->insert([ 'name' => $request->name, 'status' => $request->status ]); if($status){ $msg = "Directory added successfully"; $color = 'success'; }else{ $msg = "Failed to add directory"; $color = 'red'; } session()->put('msg',$msg); return redirect('catalog'); }</pre></p>
P粉998100648P粉998100648602 days ago701

reply all(1)I'll reply

  • P粉604848588

    P粉6048485882023-08-14 12:51:02

    Try this

    session()->flash('msg', ['text' => $msg, 'color' => $color]);

    In blade template

    <div class="col-sm-12 col-xl-12">
        @if (session()->has('msg'))
            <h5 style="color: {{ session('msg.color') }}">{{session('msg.text') }}</h5>
        @endif
    </div>

    In this code, I made sure to include the correct imports, use the correct method for data insertion, and use the flash() method instead of the put() method to temporarily store the message in the session. In addition, the color of the message is also stored in the session for better control over styling.

    Alternatively, you can try binding it using the WITH method.

    return back()->with('msg', 'Your message');

    You can use redirect() redirect()->route() and other methods. Also, please read the docs carefully, you will get a lot of ideas from it.

    reply
    1
  • Cancelreply