Skip to content
Advertisement

Laravel – how to insert json in database

here si my model

class Gallery extends Model{ protected $table = 'gallery';

protected $fillable = [
    'id','pages_id','title','subtitle'
];

protected $casts =[
    'photo'=>'array'
];

}

here is the controller

public function add_gallery(Request $request, $id)
{
    $gal = Gallery::create([
        'title' => $request['titlu'],
        'subtitle' => $request['autor'],
        'photo' => json_encode($p),
        'pages_id' => $id
    ]);

}

the line ‘photo’ => json_encode($p) does not work, it says that column photo is empty, $p is not empty

Advertisement

Answer

  1. $photo should be added to $fillable

    protected $fillable = ['id','pages_id','title','subtitle','photo'];
    
  2. Since You do using casting, You do not use json_encode/json_decode manually because Laravel is doing it for You.

    $gal = Gallery::create([
       'title' => $request['titlu'],
       'subtitle' => $request['autor'],
       'photo' => $p,
       'pages_id' => $id
    ]);
    
  3. $p variable is not present in add_gallery() method.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement