phplaravel

How to fix "Undefined variable: gambar (View: C:\xampp\htdocs\apmt\resources\views\upload.blade.php)


enter image description hereI can't understand why the variable is undefined for gambar at foreach. I'm also new to PHP Laravel 5.8.

(upload.blade.php)


<table class="table table-bordered table-striped">
    <thead>
        <tr>
            <th width="1%">File</th>
            <th>Keterangan</th>
            <th width="1%">OPSI</th>
        </tr>
    </thead>
    <tbody>

        @foreach ($gambar as $g)`here is the undefined variable`
          <tr>
              <td><img width="150px" src="{{ url('/data_file/'.$g->file) }}"></td>
              <td>{{$g->keterangan}}</td>
              <td><a class="btn btn-danger" href="/upload/hapus/{{ $g->id }}">HAPUS</a></td>
          </tr>
        @endforeach
    </tbody>
</table>

UploadController.php

    public function upload(){
        $gambar = Gambar::get();
        return view('upload',['gambar' => $gambar]);
    }   

    public function proses_upload(Request $request){
        $this->validate($request, [
            'file' => 'required|file|image|mimes:jpeg,png,jpg|max:2048',
            'keterangan' => 'required',
        ]);

        // menyimpan data file yang diupload ke variabel $file
        $file = $request->file('file');

        $nama_file = time()."_".$file->getClientOriginalName();

                // isi dengan nama folder tempat kemana file diupload
        $tujuan_upload = 'data_file';
        $file->move($tujuan_upload,$nama_file);

        Gambar::create([
            'file' => $nama_file,
            'keterangan' => $request->keterangan,
        ]);

        return redirect()->back();
    }

I expect that it will show an image from my file (data_file).The picture I upload all are just working fine. Just cannot show up in table.


Solution

  • You have missed passing the gambar in the proses_upload function and I guess you are inserting the image in the upload.blade.php

    public function proses_upload(Request $request){
    $this->validate($request, [
        'file' => 'required|file|image|mimes:jpeg,png,jpg|max:2048',
        'keterangan' => 'required',
    ]);
    
    // menyimpan data file yang diupload ke variabel $file
    $file = $request->file('file');
    
    $nama_file = time()."_".$file->getClientOriginalName();
    
            // isi dengan nama folder tempat kemana file diupload
    $tujuan_upload = 'data_file';
    $file->move($tujuan_upload,$nama_file);
    
    Gambar::create([
        'file' => $nama_file,
        'keterangan' => $request->keterangan,
    ]);
    $gamber = Gambar::get();
    return view('upload',['gambar' => $gambar]);
    
    }