简体   繁体   English

Laravel 在数据库中存储 tmp 文件名

[英]Laravel storing tmp filename in database

The upload script is working, the file also gets saved by the correct/desired name.上传脚本正在运行,文件也以正确/所需的名称保存。 However, while storing data in database, it stores .tmp filename instead但是,在数据库中存储数据时,它存储 .tmp 文件名

Controller code :控制器代码:

public function store(Request $request)
{
    $this->validate(request(), [
        'title' => 'required',
        'body' => 'required',
        'featured_image' =>'image|max:1999'
    ]);

    $post = new Post;

    if ($request->hasFile('featured_image')) {
        $image = $request->file('featured_image');
        // dd($image);

        $filename = time(). '.' .$image->getClientOriginalExtension();
        // dd($filename);
        $location = public_path('images/' . $filename);
        // dd($location);
        Image::make($image)->resize(800, 400)->save($location);
        // dd($image);

        $post->image = $filename;

        // dd($post);
    }

    auth()->user()->publish(
        new Post(request(['title', 'body', 'featured_image']))
    );

    session()->flash('message', 'your post has now been published');
    return redirect('/');
}

It's storing file name as C:\\xampp\\tmp\\phpD837.tmp .它将文件名存储为C:\\xampp\\tmp\\phpD837.tmp What's wrong?怎么了?

You create a new Post with your correct image filename:您使用正确的图像文件名创建一个新Post

$post = new Post;
....
$post->image = $filename;

But then when you save to the database, you do not use that $post data at all:但是当你保存到数据库时,你根本不使用$post数据:

auth()->user()->publish(
    new Post(request(['title', 'body', 'featured_image']))
);

So basically you create another new Post with the POSTed data, which includes the temp PHP filename, ignoring the first Post which has the filename you want.因此,基本上您使用 POST 数据创建另一个新Post ,其中包括临时 PHP 文件名,忽略具有您想要的文件名的第一个Post

Try something like:尝试类似:

$post = new Post;
....
$post->image = $filename;
$post->title = $request->title;
$post->body  = $request->body;

auth()->user()->publish($post);

I solved this problem by deleting the 'image' column in my $fillable variable.我通过删除 $fillable 变量中的“图像”列解决了这个问题。 In Model Post.php在模型 Post.php 中

protected $table = "posts";

protected $fillable = [
    'title',
    'image', //delete if exists
    'content'
];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM