简体   繁体   中英

Laravel: Redirecting user to another page with messages

Here is the excerpt from Controller code for adding a new user:

public function store()
{
    $input = Input::all();

    if (! $this->user->isValid($input))
    {
        return Redirect::back()->withInput()->withErrors($this->user->errors);
    }

    ...
}

Here the Controller code for the add a new user form:

public function create()
{
    return View::make('users.create');
}

Please notice here that I don't need to send inputs and errors to the view, but I can access it there without any issue.

But please have a look at some other code:

Here is my Controller code to delete the user:

public function destroy($id)
{
    $user = User::find($id);

    $deleted_message = 'User "' . $user->first_name . ' ' . $user->last_name . '" has been deleted.';

    User::destroy($id);

    return Redirect::route('users.index')->withMessage($deleted_message);
}

Here is my Controller code to show all users:

public function index()
{
    $users = User::all();
    return View::make('users.index')->withUsers($users);
}

Why I am not getting $message in the view to show all users?

You can send the message with this:

return Redirect::route('your-route')->with('global', 'Your message');

And get it in your template with this:

@if(Session::has('global'))
<p>{{ Session::get('global') }}</p>
@endif

Why I am not getting $message in the view to show all users?

Because you are not retrieving it. Using the withX() magic methods will put your data into the flash storage. That means, you need to retrieve it from there.

<?php 

class UserController extends Controller {

    public function index()
    {
        $message = Session::get('message');

        $users = [];

        return Redirect::make('users.index')->withUsers($users)->withMessage($message); 
    }

    public function destroy()
    {
        $deleted_message = "Some message that shows that something was deleted";

        return Redirect::route('users.index')->withMessage($deleted_message);
    }

}

See what I am doing in the first line of the controllers index() method. I am referencing the message key of the Session Storage.

We put it in there when we did:

return Redirect::route('users.index')->withMessage($deleted_message);

withX() are methods automagically made available by laravel ( see here ). Whatever is appended to with () will be stored as the key into your session data.

Relying on Magic might not be suitable if you're just starting with laravel. To better keep in mind what you're actually doing you may want to use the with() method instead, where you pass a key and a value.

return Redirect::route('users.index')->with('message', $deleted_message);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM