Search code examples
phparraysjsonlaravelundefined-variable

Undefined variable: artikel (View: C:\xampp\htdocs\uts\resources\views\layouts\home.blade.php)


Undefined variable: artikel (0)

(View: C:\xampp\htdocs\uts\resources\views\layouts\home.blade.php)

@if($artikel)
@foreach($artikel as $d)
<h3> {{ $d->judul }}</h3>
<h3> {{ $d->penulis}}</h3>
<h3> {{ $d->artikel}}</h3>
<h3> {{ $d->tanggal}}</h3>
@endforeach
@endif

This is my controller :

public function store(Request $request)
{
  $artikel = json_decode(Storage::get('public/artikel.json'), true);
  $artikeldata = (object)[
    'judul' => $request->judul,
    'slug' => Str::slug($request->judul),
    'penulis' => $request->penulis,
    'artikel' => $request->artikel,
    'tanggal' => date('Y-m-d H:i:s')
  ];

  $artikel[] = $artikeldata; 
  $artikel = json_encode($artikel, JSON_PRETTY_PRINT);
  file_put_contents('storage/artikel.json', $artikel);

  return redirect('layouts.home');
}

Solution

  •  public function store(Request $request)
        {
            $artikel = json_decode(Storage::get('public/artikel.json'), true);
            $artikeldata = (object)[
                'judul' => $request->judul,
                'slug' => Str::slug($request->judul),
                'penulis' => $request->penulis,
                'artikel' => $request->artikel,
                'tanggal' => date('Y-m-d H:i:s')
            ];
    
            $artikel[] = $artikeldata;
            $artikel = json_encode($artikel, JSON_PRETTY_PRINT);
            file_put_contents('storage/artikel.json', $artikel);
    
            return view('home',compact('artikel'));
        }