Deepak Rawat
Deepak Rawat

Reputation: 131

How to get Data from previous page in Laravel

So, i have some categories. And in each category you can add posts.

But in form page for adding posts, how to get the value of that category i.e. of previous page?

This is my form:

<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>

Link in category page to form:

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

Controller:

$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 contains link to this form page. But to get the id of the category page that is referring to this form??

Upvotes: 0

Views: 2134

Answers (1)

YouneL
YouneL

Reputation: 8351

You need to pass category_id into your link as route parameter:

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

Catch category_id in /topics/create/category_id route:

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

And then use it to create a hidden field in your form:

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

And then in your controller:

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

Upvotes: 2

Related Questions