stack stack - 1 month ago 8
PHP Question

How to pass a message to another page in Laravel?

I have a controller like this:

public function add(Requests\contactValidation $request){

if(Auth::check()) {
$new_array = array();
$new_array['name'] = $request->name;
$new_array['email'] = $request->email;
$new_array['content'] = $request->content;
contact::create($new_array);
return back();
} else {
return back()->withError('you are not log in');
}
}


And I have this view:

<?php
echo "<pre>";
print_r( $errors->all());
?>


Result:

Array
(
[0] => you are not log in
)





My question: How can I set a name to that message? I want something like this result:

Array
(
[Name] => you are not log in
)

Answer

This is what I usually do:

return Redirect::to('users/register')->with('message', 'The following errors occurred')->withErrors($validator)->withInput();

So, basically you can return with message/messages which is stored as a session and obviously also the errors. Also, you can check the following link to the documentation for detailed understanding.

Further, you can print them as:

@if(Session::has('message'))
      <p class="alert">{!! Session::get('message') !!}</p>
      @foreach($errors->all() as $error)
          <p>{!! $error !!}</p>
      @endforeach
@endif

Obviously, you can change it as per your requirement. Hope it helps.

Comments