简体   繁体   中英

Uploading and storing an image in Laravel 5.8 image not storing in database or file path

Fairly new to laravel I want to upload an image and store it in the database and file path. First issue I am having is the image is not appearing in the array for the validateRequest function so it is returning as NULL in the database. Second issue is I tried to use storage:link to store all the uploaded images but can't seem to store the images and unsure what file path I meant to use.

    public function validateRequest()
    {
        $validated = request()->validate([
            'title' => 'required|string',
            'h1' => 'required|string',
            'page_title' => 'required|string',
            'meta_description' => 'required|string',
            'content' => 'required|string',
            'active' => 'integer'
        ]);

        if (request()->hasFile('image')){
            $validated = request()->validate([
                'image' => 'sometimes|file|image|mimes:jpeg,png,jpg,gif,svg|max:5000'
            ]);
        }

        // Check if active is ticked
        $validated['active'] = isset(request()->active[0]) ? 1 : 0;

        // Create slug from title
        $validated['slug'] = Str::slug(request()['title'], '-');

        return $validated;
    }
    public function storeImage($post)
    {
        if (request()->hasFile('image')) {
            $post->update([
                'image' => request()->image->storeAs('/images/uploads/posts', 'public')
            ]);

        }
    }

I have tried putting the image with the rest of the fields in the $validated = request()->validate but then it says "this image must be an image" even though an image has been selected. Really appreciate the help thank you.

First problem is validate. Please add this in your form

<form ... enctype="multipart/form-data">

Second problem is to solve like this. In your controller call function like this

$productImage = $request->file('your_image_name');

if (is_file($productImage)) {
    $imageUrl = $this->productImageUpload($productImage);
    $product->your_database_field_name = $imageUrl;
}


protected function productImageUpload($productImage)
{
    $imageName = $productImage->getClientOriginalName();
    $directory = 'your_file_path/your_file_path/';
    $imageUrl = $directory . $imageName;
    $productImage->move($directory, $imageName);
    return $imageUrl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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