如何从Laravel的上一页获取数据

时间:2017-12-26 17:32:07

标签: php laravel laravel-5

所以,我有一些类别。在每个类别中,您都可以添加帖子。

但是在添加帖子的表单页面中,如何获取该类别的值,即上一页的值?

这是我的表格:

<div class="container">
    {!! Form::open(['action' => 'TopicController@store', 'method' => 'POST']) !!}
        <div class="form-group">
            {{ Form::label('title', 'Title') }}
            {{ Form::text('title', '', ['class' => 'form-control', 'placeholder' => 'Title of the Post']) }}
        </div>
        <div class="form-group">
            {{ Form::label('desc', 'Desc') }}
            {{ Form::textarea('desc', '', ['class' => 'form-control', 'placeholder' => 'Description of the Post']) }}
        </div>
        {{ Form::submit('Submit', ['class' => 'btn btn-default']) }}
    {!! Form::close() !!}
</div>

在类别页面中链接到表单:

<a href="/topics/create">Create New Post</a>

控制器:

$this->validate($request, [
            'title' => 'required',
            'desc' => 'required',
        ])
$topic = new Topic;
$topic->topic_title = $request->input('title');
$topic->topic_body = $request->input('desc');
$topic->user_id = auth()->user()->id;
$topic->save();
return redirect('/')->with('Seccess', 'Topic Created');

show.blade.php包含此表单页面的链接。但要获取引用此表单的类别页面的ID ??

1 个答案:

答案 0 :(得分:2)

您需要将category_id作为路由参数传递到您的链接:

<a href="/topics/create/{{ $category_id }}">Create New Post</a>

/topics/create/category_id路线中抓住category_id:

Route::post('/topics/create/{category}', 'TopicsController@create');

然后使用它在表单中创建一个隐藏字段:

<div class="container">
    {!! Form::open(['action' => 'TopicController@store', 'method' => 'POST']) !!}
    {{ Form::hidden('category_id', $category_id) }}
    ...
</div>

然后在你的控制器中:

...
$topic->category_id = $request->input('category_id');
$topic->user_id = auth()->user()->id;
$topic->save();
...