Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Derived property does not get initialized from parent constructor

In my general controller GeneralController:

use App\Http\Controllers\Controller;
class GeneralController extends Controller
{
    protected $onLine = null;

    public function __construct(Request $request)
    {
        $this->onLine = OnLine::domain($request->domain)->first();
    }
}

In my other controller, extends GeneralController:

use App\Http\Controllers\OnLine\ItemController;
class ItemController extends GeneralController
{
    public function getItem(Request $request)
    {
        dd($this->onLine); // but returns null :(
    }
}

I already checked, that OnLine::domain($request->domain)->first(); returns data, which it does.

like image 790
FatBoy Avatar asked May 28 '26 02:05

FatBoy


2 Answers

I'm not sure what do you expect with request->domain. Is this an input or do you expect the current domain?

If this is an input, that's correct. If you want the current domain you should use parse_url($request->url(), PHP_URL_HOST).


When you use ->first() (or find()) method, if the query return 0 results, the value of 'first' will be null.

class GeneralController extends Controller
{
    protected $onLine;

    public function __construct(Request $request)
    {
        $this->onLine = OnLine::domain($request->domain)->first();
    }
}

There is nothing wrong with your code. My guess is that you forgot to send the "domain".

To make it easier to debug, just change your constructor with a hardcoded value (instead of sending a $request->domain, use any value that is already in "OnLine" table).

After that, check if you have any value from $request. dd($request->all()); If this is an empty array, you forgot to send the domain.

And make sure you use use Illuminate\Http\Request;.

like image 76
Eduardo Stuart Avatar answered May 30 '26 16:05

Eduardo Stuart


Is this a typo in your ItemController?

use App\Http\Controllers\OnLine\ItemController;

It should be GeneralController, right?


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!