Search code examples
phplaravellaravel-5

How to use two `with` in Laravel?


I try to show two flash messages in Laravel using with:

return redirect('cabinet/result')->with('user', $client->unique_code)->with('fio', $client->name.' '.$client->secondname. ' '.$client->patronymic);

Then I display this as:

{{ session('fio') }}  {{ session('unique_code') }}

It shows me nothing


Solution

  • Firstly, when you pass data with the method 'with' to a view, it does not get stored in the session, it is just made available as a variable with the same name to the view that gets loaded after the redirect takes place.

    You have two options:

    Passing an array of key value pairs to the view

    You may pass an array of data to views:

    return view('greetings', ['name' => 'Victoria', 'last_name' => 'Queen']);
    

    As you can see by the way the method is implemented in {root}/vendor/laravel/framework/src/Illuminate/View/View.php

    /**
     * Add a piece of data to the view.
     *
     * @param  string|array  $key
     * @param  mixed   $value
     * @return $this
     */
    public function with($key, $value = null)
    {
        if (is_array($key)) {
            $this->data = array_merge($this->data, $key);
        } else {
            $this->data[$key] = $value;
        }
    
        return $this;
    }
    

    the method accepts either a key value pair, or an array. All the keys of this array will be available in the view that is loaded next as php variables with the same name (of course you need to append the dollar sign to the calls in the view). So in the 'greetings' view you would retrieve them as such:

    $variable1 = {{ $name }}
    
    $variable2 = {{ $last_name }}
    

    Flashing an array of key value pairs to the next session

    You can do pretty much the same using the flashInput method that is found in {root}/vendor/laravel/framework/src/Illuminate/Session/Store.php:

    /**
     * Flash a key / value pair to the session.
     *
     * @param  string  $key
     * @param  mixed   $value
     * @return void
     */
    public function flash($key, $value)
    {
        $this->put($key, $value);
    
        $this->push('_flash.new', $key);
    
        $this->removeFromOldFlashData([$key]);
    }
    

    You would do that as such:

    $request->session()->flashInput('flashData' => ['key1' => value1, 'key2' => value2]);
    

    The difference here is that the data would not be available as variables to your loaded view. Instead they would be stored in an associative array in the session and you would retrieve the stored values this way:

    $variable1 = {{ session('flashData['key1']) }}
    
    $variable2 = {{ session('flashData['key2']) }}
    
    Resources

    If you feel that this solved your problem please mark the answer as accepted :)