Как исправить "Неопределенная переменная: gambar (Вид: C: \ xampp \ htdocs \ apmt \ resources \ views \ upload.blade.php) - PullRequest
3 голосов
/ 07 октября 2019

enter image description here Я не могу понять, почему переменная не определена для gambar при foreach. Я также новичок в 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();
    }

Я ожидаю, что он покажетизображение из моего файла (data_file). Картинка, которую я загружаю, все работает нормально. Просто не может отображаться в таблице.

Ответы [ 4 ]

1 голос
/ 07 октября 2019

Вы пропустили передачу gambar в функцию proses_upload, и я полагаю, вы вставляете изображение в 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]);

}
0 голосов
/ 07 октября 2019

Пожалуйста, сделайте это;

$gambar = Gambar::all();
return view('upload',compact('gambar'));

Сначала верните переменную в вашем контроллере, чтобы проверить, какие значения она возвращает, так же, как я это делал ниже, если она возвращает, используйте:

$gambar = Gambar::all();
return $gambar;
0 голосов
/ 07 октября 2019
public function upload()
{
$gambar = Gambar::get();
return view('upload',compact('gambar'));
OR
return viw('upload')->with('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()->route('upload-view');
} 

В web.php

  Route::get('upload',UploadController@upload)->name('upload-view');

На ваш взгляд

  <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)
                <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>
0 голосов
/ 07 октября 2019

пожалуйста, отредактируйте ваш пост и укажите код вашего контроллера в вопросе. но по моему. $ gambar не прошел правильно в вашем контроллере. шаг может помочь:

  1. проверьте ваш контроллер, если $ gambar был правильно передан вашему взгляду.
  2. в laravel. Вы можете использовать compact или with() метод для передачи переменных. пример в контроллере:

    $gambar = 'path/to/file/gambar.png'
    return view('index',compact('gambar')) // it will passed $gambar in index.blade
    

или

$gambar = 'path/to/file/gambar.png'
return view('index')->with('gambar',$gambar); // it's also passed $gambar in index.blade
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...