【问题标题】:Issue with laravel - str_randomlaravel 的问题 - str_random
【发布时间】:2016-04-12 08:18:09
【问题描述】:

我有这个代码可以用 Laravel 上传图片:

     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

为什么,问题是什么? 为什么不在数据库(DiYhh.png)的image 列中存储相同的名称,而不是 /tmp/... ???

【问题讨论】:

  • 您将更改保存到数据库的哪个位置?在您的代码 sn-p 中,您只需将 $article['image'] 设置为文件名,但您没有显示实际保存它的位置。
  • 我把它保存到文章表 - 列图片...
  • 能否请您也将该代码添加到问题中?
  • 谢谢,我现在可以看到问题了。我已经为你写了一个答案。

标签: php laravel variables random


【解决方案1】:

在您的代码中,您首先将文章设置为某个值,然后再覆盖它。所以当你这样做时:

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

您已成功将文件移动到正确的位置。但是再往下几行,你可以这样做:

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

现在,代码忘记了 $article['photo'] 包含您想要的文件名 - 因为它已被覆盖。

我建议将新的文章行进一步移到顶部,然后对该对象进行更改,最后在您验证所有内容后保存它。

【讨论】:

  • 现在我收到错误:违反完整性约束:1048 列“照片”不能为空
  • 好吧,你必须在之后再次设置照片变量。例如:$article = new Article($request->all()); 然后是 $article->photo = $filename;,最后是 $article->save(); 来持久化它。这假设您已经设置了文件名,并且您可以根据需要在其间添加其他行。
猜你喜欢
  • 1970-01-01
  • 2014-05-25
  • 2018-09-29
  • 1970-01-01
  • 2018-03-24
  • 2017-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多