Thursday, March 16, 2017

Why is the hidden field in the Laravel Model not working when set dynamically?

I am writing a function in the model where I need a data something like this.

{"id": 1, "level_id": "1"}

So, the query is something like this:

public function showAdvancedRoutes(array $requestArray = [], $journey_id = null, $level_id = null) {
    $queryResults = $this -> with(['level' => function ($query) use($journey_id, $level_id) {
        $query -> where('levels.level_number', $level_id)
            -> where('levels.journey_id', $journey_id);
    }]) -> get() ;
    return (sizeof($queryResults) == 0) ? null : ((sizeof($queryResults) > 1) ? ["Multiple Records. Please contact developer."] : $queryResults[0]);
}

where

public function level() { return $this->belongsTo('App\Model\Level', 'level_id'); }

Now THE REAL PROBLEM IS:

when I write, protected $hidden = ['level']; I the desired results of {"id": 1, "level_id": "1"}. But, when I do something like this:

public function showAdvancedRoutes(array $requestArray = [], $journey_id = null, $level_id = null) {
    $this -> setHidden(['level']);
    //#query logic
}

I get, {"id": 1, "level_id": "1", "level": {"id": 1}}.

So, my real doubt is why is the hidden attribute not working while Query building?

In both cases, whether I write protected $hidden = ['level']; or I setHidden dynamically, the dump of the model is same.

["hidden":protected]=>array(1){[0]=>string(5) "level"}

But, I am getting results different in two cases. Is this a bug or an I doing something wrong?



via Prateek Shankar

Advertisement