Laravel从输入数组

时间:2017-06-16 14:38:53

标签: php laravel request

我有一个包含匹配变量的隐藏字段。

{{ Form::input('hidden', 'match', $match, ['id' => 'match']) }}

如何在商店方法中检索“主页”字段等?

public function store(Request $request)
    {
        Log::info($request->match);

        Ticket::create([
            'home' => $request->match->home,
            'away' => $request->away,
            'place' => $request->place,
            'price' => $request->price,
            'section' => $request->section,
            'amount' => $request->amount,
            'competition' =>  $request->competition
        ]);

        return redirect('/');
    }

2 个答案:

答案 0 :(得分:0)

您可以在输入中存储已编码的json字符串:

{{ Form::input('hidden', 'match', $match, json_encode(['some' => 'thing'])) }}

您需要再次对其进行解码:

$match = json_decode($request->match)

然后你可以:

$match['some'];

答案 1 :(得分:0)

现在的代码将无效。

{{ Form::input('hidden', 'match', $match, ['id' => 'match']) }}

将存储一个字符串。在您的Controller函数中,您尝试访问对象参数$request->match->home。做这样的事情的唯一方法是使用json_encoding / json_decoding。 $match应该是json_encode对象,而$request->match应该在你的Controller中解码。

可能的解决方案:

//in your blade file
{{ Form::input('hidden', 'match', json_encode($match), ['id' => 'match']) }}

//in your controller
public function store(Request $request)
{
    $match = json_decode($request->match);

    Ticket::create([
        'home' => match->home,
        'away' => $request->away,
        'place' => $request->place,
        'price' => $request->price,
        'section' => $request->section,
        'amount' => $request->amount,
        'competition' =>  $request->competition
    ]);

    return redirect('/');
}

如果您不喜欢在刀片文件中使用php代码的解决方案,那么更好的解决方案是序列化您的Match对象:

$match= App\Match::find(1);

$match = $match->toJson();
return view('edit', ['match' => $match])