1

I'm starting with Laravel and i need to show the output of a post request into the view. My controller file returns an array with a message, like this:

return redirect('/myroute')
            ->with('message', [
                'type' => 'success', 
                'text' => 'It works'
            ]);

In my view file, i'm trying to grab the message text, but no success. See my code below

@if(Session::has('message'))
    {{ $msg = Session::get('message') }}
    <h4>{{ $msg->text }}</h4>
@endif

The point is: The condition works, if i changed the {{$msg->text}} to any text it works, but when i try to get the message text, it returns an error:

htmlspecialchars() expects parameter 1 to be string, array given

So, any help is apreciated. If more information is needed, just ask.

PS: i checked this question, but no success at all EDITED: PS2: Can't change controller structure

danielarend
  • 1,379
  • 13
  • 26
  • Have you checked what `$msg` exactly contains? Try dumping it in the controller to see whether it is an array, an object, a string,...... – Nico Haase Nov 09 '18 at 14:53
  • @NicoHaase i tried to dump it {{var_dump($msg)}} inside template but still got the same error – danielarend Nov 09 '18 at 15:14

2 Answers2

4

Try accessing the array as follows:

<h4>{{ $msg['text'] }}</h4>

or just pass an array with the items

->with([
            'type' => 'success', 
            'text' => 'It works'
        ]);

//in the view
@if(session()->has('text'))
    <h4> {{ session('text') }} </h4>
@endif

-- EDIT

iterate than over the session like so:

@foreach (Session::get('message') as $msg)
  {{$msg['text']}}
@endforeach

you can read more about that here

nakov
  • 13,938
  • 12
  • 60
  • 110
  • It didn't wok for me, same error. Can't change controller structure. I tried also {{$msg->text}} and error persist. – danielarend Nov 09 '18 at 14:46
  • Then you have to iterate over the session in order to access your items. Look at my Edit above – nakov Nov 09 '18 at 14:53
  • Thanks a lot, but still not working, Error message now is 'Illegal string offset 'text'' – danielarend Nov 09 '18 at 15:09
  • try to `var_dump` the content of the `$msg` within the view and see what it has, something is missing there so I cannot debug it when I don't have the code. – nakov Nov 09 '18 at 16:04
0

Do this instead

return redirect('/myroute')->with('success','It worked');

Then on your view

{{session('success')}}
Paul Mikki
  • 68
  • 3