Laravel hide foreign_key field on JSON response but access to create new entry

I would like to hide my foreign_key on JSON response :

return Response::json(['type' => 'success', 'data' => $my_object, 'status' => 200], 200);

I added in my model :

protected $hidden = ['fk_category_id'];

My foreign key is hide !

But in my controller I have this :

$new_question = $this->question_repository->create([
    'text' => $question->text,
    'fk_category_id' => 2,
]);

The problem : I don't create a new object in my database, the field fk_category_id is NULL, I think I have no access to this field

My foreign key in my JSON response it's hide (great!) but I can't set my foreign key in my database when I created new entry.

Upvotes: 0

Views: 565

Answers (2)

Matius Nugroho Aryanto
Matius Nugroho Aryanto

Reputation: 901

add this to your model

protected $fillable = [..,'fk_category_id','text'];

you are attempting to do mass assignment, fillable is a whitelist which field will be fillable by mass assignment. .. means you can add whatever field you want there.

Upvotes: 1

delboy1978uk
delboy1978uk

Reputation: 12382

I saw your entity in your last (deleted) question. Add a setter function, then you can call that! Your protected and private properties will remain hidden!

class MyEntity
{
    private $hidden;

    public function getHidden()
   {
        return $this->hidden;
   }

    public function setHidden($value)
    {
        $this->hidden = value;
    }

   // the rest of your code etc
}

Upvotes: 0

Related Questions