Laravel controller cannot return session variables
P粉998100648
2023-08-13 20:34:28
<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>
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
WITHmethod.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.