简体   繁体   中英

how to assign session data in class property in laravel php

I'm trying to set session data to class property in Laravel controller but getting null in controller functions please help me with how to deal with that or suggest me best approach for that.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;

class InventoryController extends Controller
{
    public $company_id;
    public function __construct()
    {   
        $company_id = session('last_company');
        $this->company_id = $company_id;
    }
    public function index()
    {
        dd($this->company_id);
        $products = Product::where('company_id',$this->company_id)->get();
        // dd($products);
        return view('Inventory.view',compact($products));
    }
}

Im getting $this->company_id as null in index function but i can get data when dd(session('last_company')) in index function

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;

class InventoryController extends Controller
{
    public $company_id;
    public function __construct()
    {   
        $company_id = session('last_company');
        $this->company_id = $company_id;
    }
    public function index()
    {
        dd(session('last_company'));
        $products = Product::where('company_id',session('last_company'))->get();
        return view('Inventory.view',compact($products));
    }
}

The reason you get null is that the session manager, Illuminate\Session\Middleware\StartSession is a middleware and it's not bootstrapped at that point. Furthermore, there is no reason to keep session data in a controller because the controller's __destruct method will be called by the time you return the response back to the route's chain. You can read more here . Instead of that, you can try this,

use Illuminate\Http\Request;
public function index(Request $request)
{
    $products = Product::where('company_id', $request->session()->get('company_id')->get();
    return view('Inventory.view',compact($products));
}

You may want to pass a default value to second argument of get method to be returned if the specified value does not exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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