phplaravellaravel-5laravel-viewslaravel-session

Laravel - set session from form input


I cannot display session value in my view. I only want to display it to see if it's correctly set inside the controller. Is it correctly set in controller? How can I check? I have this in view:

<div class="panel panel-success">
                <form action="{{ route('get_table') }}" method="POST">
                    {{ csrf_field() }}
                    @foreach($tables as  $data)                   
                    <button type="submit" name="tables" class="btn btn-primary" value="{{ $data->id }}">
                        {{$data->name }}
                    </button>
                    @endforeach
                </form>
                {{ Session::get('table_id') }}
            </div>

This in ListController:

public function index() {
    $tables = DB::table('tables')->get();
    return view('welcome', compact('tables'));
}

public function getTable(Request $request) {
    $table_id = $request->get('tables');
    $request->session()->put('table_id', $table_id);
}

And this in web.php routes:

Route::get('/', 'ListController@index')->name('get_table');
Route::post('/', 'ListController@getTable');

I even tried

public function getTable(Request $request) {
    $request->session()->put('table_id', '1234');
}

Nothing shows up in the view at {{ Session::get('table_id') }}

What am I doing wrong?


Solution

  • You can try this:

    public function getTable(Request $request) {
        $table_id = $request->get('tables');
        return redirect()->back()->with('table_id',$table_id);
    }
    

    if you want to redirect to specific route then:

    public function getTable(Request $request) {
        $table_id = $request->get('tables');
        return redirect()->route('RouteName')->with('table_id',$table_id);
    }
    

    and then in view:

      @if(Session::has('table_id'))
    
          {{ Session::get('table_id') }}
    
      @endif
    

    Hope you got your answer