2016-04-12 41 views
0

我有這樣的代碼上傳圖像與Laravel:問題與laravel - str_random

 public function store(Requests\ArticleRequest $request) 
    { 
     $article['photo']= 'http://nationaluasi.com/dru/content/hotelIcon.png'; 
     $file = array('image' => $request->file('image')); 
     // setting up rules 
     $rules = array('image' => 'required',); //mimes:jpeg,bmp,png and for max size max:10000 
     // doing the validation, passing post data, rules and the messages 
     $validator = Validator::make($file, $rules); 
     if ($validator->fails()) { 
     // send back to the page with the input data and errors 
     $article['photo'] = null; 

     } 
     else { 
    // checking file is valid. 
     if ($request->file('image')->isValid()) { 
     $destinationPath = public_path().'/images'; // upload path 
     $extension = $request->file('image')->getClientOriginalExtension(); // getting image extension 
     $article['photo'] = str_random(5).'.'.$extension; // renameing image 
     $request->file('image')->move($destinationPath, $article['photo']); // uploading file to given path 
     // sending back with message 

     } 
     else { 

     } 
    } 



     $article = new Article($request->all()); 
     $article['key']= str_random(30); 


     Auth::user()->articles()->save($article); 

     Alert::success('nnn','Good job!')->persistent("Close"); 



     return redirect('auctions'); 
    } 

所以一切都很好用的圖片上傳,但是當我看到我的/public/images文件夾中的圖像具有名稱:DiYhh.png但在數據庫中存儲:/tmp/phpVu3QOa

爲什麼,探針是什麼? 爲什麼不在數據庫中的image列中存儲相同的名稱(DiYhh.png)而不是/ tmp/...?

+0

你在哪裏堅持改變數據庫?在您的代碼片段中,您只需將'$ article ['image']'設置爲文件名,但不會顯示實際保存的位置。 –

+0

我將它保存到文章列表中 - 列圖像... – Andrew

+0

您可以將該代碼添加到問題中嗎? –

回答

1

在您的代碼中,您首先將文章設置爲某種東西,然後覆蓋它。所以當你這樣做時:

$article['photo'] = str_random(5).'.'.$extension; 
$request->file('image')->move($destinationPath, $article['photo']); 

你正在成功地將文件移動到正確的位置。但隨後幾行進一步下跌,你這樣做:

$article = new Article($request->all()); 

現在,代碼已經忘記了$article['photo']包含你想要的文件名 - 因爲它被覆蓋。

我建議將新的文章行進一步移動到頂端,然後對該對象進行更改,最後在您驗證完所有內容後進行保存。

+0

謝謝你是一個問題... – Andrew

+0

現在我得到了錯誤:完整性約束違規:1048列的'照片'不能爲空 – Andrew

+0

那麼,你必須事後再設置照片變量。例如:'$ article = new Article($ request-> all());'然後'$ article-> photo = $ filename;',然後最後'$ article-> save();'來堅持它。假設你已經設置了文件名,並且可以根據需要放置其他行。 –