简体   繁体   English

表单 - 从控制器传递数组到视图 - PHP - Laravel

[英]Form - Passing array from controller to view - PHP - Laravel

I'm really new to Laravel, and I'm not sure that I know what I'm doing. 我是Laravel的新手,我不确定我知道自己在做什么。 I have a form in my main view. 我在主视图中有一个表单。 I'm passing the input to a controller, and I want the data to be displayed in another view. 我将输入传递给控制器​​,我希望数据显示在另一个视图中。 I can't seem to get the array from the controller to the second view. 我似乎无法从控制器到第二个视图获取数组。 I keep getting 500 hphp_invoke. 我一直得到500 hphp_invoke。 Here's where I'm passing the array from the controller to view2. 这是我将数组从控制器传递到view2的地方。

public function formSubmit()
{
    if (Input::post())
    {
        $name = Input::get('name');
        $age = Input::get('age');
        $things = array($name, $age);
        return View::make('view2', array('things'=>$things));
    }
}

view1.blade.php view1.blade.php

{{ Form::open(array('action' => 'controller@formSubmit')) }}
    <p>{{ Form::label('Name') }}
    {{ $name = Form::text('name') }}</p>
    <p>{{ Form::label('Age') }}
    {{ $age = Form::text('age') }}</p>
    <p>{{ Form::submit('Submit') }}</p>
{{ Form::close() }}

My view2.php file is really simple. 我的view2.php文件非常简单。

<?php
    echo $name;
    echo $age;
?>

Then in routes.php 然后在routes.php中

Route::get('/', function()
{
    return View::make('view1');
});
Route::post('view2', 'controller@formSubmit');

Why isn't this working? 为什么这不起作用?

try with() 尝试用()

$data = array(
    'name'  => $name,
    'age' => $age
);

return View::make('view2')->with($data);

on view get :- echo $data['name']; 在视图上得到: - echo $ data ['name']; echo $data['age']; echo $ data ['age'];

or 要么

return View::make('view2')->with(array('name' =>$name, 'age' => $age));

get on view :- 继续观察: -

echo $name;
echo $age;

For more Follow here 更多关注此处

You need to use: 你需要使用:

return View::make('view2')->with(['name' => $name, 'age' => $age]);

to use 使用

$name and $age in your template 模板中的$name$age

Since $things is already an array so you may use following approach but make the array associative: 由于$things已经是一个array因此您可以使用以下方法,但使数组关联:

$name = Input::get('name');
$age = Input::get('age');
$things = array('name' => $name, 'age' => $age);
return View::make('view2', $things);

So, you can access $name and $age in your view . 因此,您可以在view访问$name$age Also, you may try this: 另外,你可以试试这个:

return View::make('view2')->with('name', $name)->with('age', $age);

In your controller, use 在您的控制器中,使用

return View::make('view2')->with($things);

In your view, you can now access each attribute using 在您的视图中,您现在可以使用访问每个属性

@foreach($things as $thing)
    <p>{{ $thing->name }}</p>
    <p>{{ $thing->age }}</p>
@endforeach

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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