如何在 Laravel 中使用两个 `with`?

How to use two `with` in Laravel?

我尝试使用 with:

在 Laravel 中显示两条即时消息
return redirect('cabinet/result')->with('user', $client->unique_code)->with('fio', $client->name.' '.$client->secondname. ' '.$client->patronymic);

然后我将其显示为:

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

它什么也没给我显示

首先确保你的查询return数据。
在我的项目中,我使用简单的方法。

$user = $client->unique_code; //now user has the code
$fio = $client->name.' '.$client->secondname. ' '.$client->patronymic;
//please make sure this returns your indented result.

return redirect('cabinet/result')->with('user', $user)->with('fio',$fio );

我希望这会奏效,

试试这个代码:

$user = 'user';
$fio = 'fio';

return redirect('cabinet/result')
           ->with('user', $user)
           ->with('fio', $fio);

查看:

{{ Session::get('user') }} {{ Session::get('fio') }}

首先,当您使用方法 'with' 将数据传递给视图时,它不会存储在会话中,它只是作为同名变量提供给加载的视图重定向发生后。

您有两个选择:

将键值对数组传递给视图

您可以将数据数组传递给视图:

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

正如你所看到的方法在{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;
}

该方法接受键值对或数组。该数组的所有键将在接下来加载的视图中作为具有相同名称的 php 变量提供(当然,您需要将美元符号附加到视图中的调用)。因此,在 'greetings' 视图中,您可以这样检索它们:

$variable1 = {{ $name }}

$variable2 = {{ $last_name }}

将键值对数组刷写到下一个会话

您可以使用 {root}/vendor/laravel/framework/src/Illuminate/Session/Store.php:

中的 flashInput 方法执行几乎相同的操作
/**
 * 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]);
}

你会这样做:

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

这里的区别在于数据不会作为变量提供给您加载的视图。相反,它们将存储在会话中的关联数组中,您可以通过这种方式检索存储的值:

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

如果您觉得这解决了您的问题,请将答案标记为已接受:)