So my controller looks as follows:
use Illuminate\Http\Request;
use Illuminate\Cookie\CookieJar;
use Cookie;
class MyController extends Controller {
public function __construct(CookieJar $cookieJar)
{
$this->id = $this->getID();
$this->cookieJar = $cookieJar;
}
private function getID()
{
if (!isset($_COOKIE["ID"])){
$id = 20;
$this->cookieJar->queue('ID', $id, 60);
}
return $id;
}
But I keep getting an error
Undefined property: App\Http\Controllers\MyController::$cookieJar
In getID function.
What am I doing wrong? Would highly appreciate any possible help!
Basically problem in your code not that cookieJar class. Below is the correct code for controller:
use Illuminate\Http\Request;
use Illuminate\Cookie\CookieJar;
use Cookie;
class MyController extends Controller {
protected $id;
protected $cookieJar;
public function __construct(CookieJar $cookieJar)
{
$this->cookieJar = $cookieJar;
$this->id = $this->getID();
}
private function getID()
{
if (!isset($_COOKIE["ID"])){
$id = 20;
$this->cookieJar->queue('ID', $id, 60);
}
return $id;
}
When we are using any property in all the functions of controllers for carry some value then we have to define these properties. Please check my code.
One more thing, the order of properties also incorrect in constructor method. Because you are using a function getID()
which is using $cookieJar
property. So you have to define that property first then use second property $id
in constructor method.
I think this will be helpful for you.