2016-12-09 4 views
1

Это то, что у меня есть: таблицыLaravel 5,2 - Загрузка файлов в базу данных

базы данных с именем lamanInformasi, который имеет следующие поля: id, judul, isi, created_at, updated_at.

Это то, что я хочу:

Пользователь может загрузить несколько документов или файлов изображений, а также файлы будут сохранены в базе данных. Имена файлов будут сохранены в поле isi, а сами файлы будут сохранены в папку с именем propic. Пользователь также может отображать все данные из базы данных на веб-сайте.

Это мои коды:

create.blade.php

<form action="[email protected]" method="post" enctype="multipart/form-data"> 
    <input type="file" name="image"><br /> 
    <input type="submit" name="submit" value="Submit"> 
</form> 

lamanInformasiController.php

public function index(Request $request) 
{ 
    $file = new file; 
    if (Input::hasFile('image')) 
    { 
     $destinationPath = public_path().'/propic/'; 
     $name = Input::file('image')->getClientOriginalName(); 
     $extension = Input::file('image')->getClientOriginalExtension(); 

     $file = Input::file('image')->move($destinationPath, $name . "." . $extension); 
    } 
    $file -> isi = $request->get($file); 
    $file -> save(); 

    $lamanInformasi = LamanInformasi::all(); 
    return view('upload.index', compact('lamanInformasi')); 
} 

index.blade.php

<table class="table table-striped table-bordered" border= "1px solid black"> 
    <thead> 
     <tr> 
      <td>ID</td> 
      <td>Judul</td> 
      <td>Isi</td> 
      <td>Created At</td> 
      <td>Updated At</td> 
     </tr> 
    </thead> 
    <tbody> 
     @foreach($$lamanInformasi as $key => $value) 
     <tr> 
      <td>{{$value->id}}</td> 
      <td>{{$value->judul}}</td> 
      <td>{{$value->isi}}</td> 
      <td>{{$value->created_at}}</td> 
      <td>{{$value->updated_at}}</td> 
     </tr> 
     @endforeach 
    </tbody> 
</table> 

Когда я запускаю его, у меня есть эта ошибка:

ErrorException in ParameterBag.php line 90: 
array_key_exists(): The first argument should be either a string or an integer 

У меня есть это в ParameterBag line 89-91

public function get($key, $default = null) 
{ 
    return array_key_exists($key, $this->parameters) ? $this->parameters[$key] : $default; 
} 

Вот мои вопросы:

Как к f ix эта ошибка? Правильно ли я сделал код для загрузки файлов? Потому что я пробовал аналогичный код, и он не работает. Спасибо

+0

Способ, которым array_key_exists обрабатывает ключи с нулевым, float, boolean и «integer-present string», сам по себе несовместим, а в случае с bool и float - с тем, как они преобразуются при использовании в качестве смещения массива. – FullStack

+0

@FullStack Извините, я не понимаю. Что мне делать? –

+0

посмотрите на эту страницу http://php.net/manual/en/function.array-key-exists.php#90687 – FullStack

ответ

0

Есть несколько вещей, о которых вам нужно позаботиться. Попробуйте код, как показано ниже

LamanInformasiController.php - имена контроллеров, как правило, капитализируются

class LamanInformasiController extends Controller 
{ 
    /** 
    * @var LamanInformasi - include the use statement above for the model. 
    */ 
    protected $model; 

    /** 
    * Inject (model)LamanInformasi while instantiating the controller. 
    * @param LamanInformasi $model 
    */ 
    public function __construct(LamanInformasi $model) 
    { 
     $this->model = $model; 
    } 

    public function index() 
    { 
     $lamanInformasi = $this->model->all(); 
     return view('upload.index', compact('lamanInformasi')); 
    } 


    public function store(Request $request) 
    { 
     if (Input::hasFile('image')) 
     { 
      $destinationPath = public_path().'/propic/'; 
      $name = Input::file('image')->getClientOriginalName(); 
      $extension = Input::file('image')->getClientOriginalExtension(); 
      $fileName = $name.'.'.$extension; 

      //store the file in the $destinationPath 
      $file = Input::file('image')->move($destinationPath, $fileName); 

      //save a corresponding record in the database 
      $this->model->create(['isi'=> $fileName]); 

      //return success message 
     } 
     //return failure message 
    } 

} //don't forget to include the use statement for Input or write \Input 

Затем в index.blade.php

<table class="table table-striped table-bordered" border= "1px solid black"> 
<thead> 
    <tr> 
     <td>ID</td> 
     <td>Judul</td> 
     <td>Isi</td> 
     <td>Created At</td> 
     <td>Updated At</td> 
    </tr> 
</thead> 
<tbody> 
    @foreach($lamanInformasi as $file) 
    <tr> 
     <td>{{$file->id}}</td> 
     <td>{{$file->judul}}</td> 
     <td>{{$file->isi}}</td> 
     <td>{{$file->created_at}}</td> 
     <td>{{$file->updated_at}}</td> 
    </tr> 
    @endforeach 
</tbody> 

и ваш форма должна быть соответственно

<form action="/upload8" method="post" enctype="multipart/form-data"> 
<input type="file" name="image"><br /> 
<input type="submit" name="submit" value="Submit"> 

Это должно работать, не проверял, хотя. Дайте мне знать, если в противном случае.

+0

Я допустил ошибку. Я должен был помещать код внутри 'index' в' LamanInformasiController'' в функцию 'store', поэтому я его перемещаю. Он работает нормально, пока я не выберу файл и не нажал кнопку «Отправить». У меня есть эта ошибка 'NotFoundHttpException в строке RouteCollection.php 161' –

+0

У меня это в' routes.php' 'Route :: resource ('/ upload8', 'LamanInformasiController'); ' –

+0

Если вы используете' Route :: resource', то вы должны следовать за соглашением REST и обрабатывать сохранение загруженного файла в методе 'store' вашего' LamanInformasiController' и изменять действие формы – Donkarnash