简体   繁体   中英

upload image as optional in laravel 8

I want to upload image using laravel 8, and I use following code:

    $post = new Post;

    $upload_image_name = time().'_'.$req->image_name->getClientOriginalName();
    $req->image_name->move('uploads', $upload_image_name); 

    $post->title = $req->input('title');
    $post->image_name = $upload_image_name;
    $post->save();

It is working fine, but I got error Call to a member function getClientOriginalName() on null while image is empty.

It's because, suprise, image is empty while image is empty

Add condition to check uploaded image

$post = new Post;
$post->title = $req->input('title');
if($req->image_name)
    $upload_image_name = time().'_'.$req->image_name->getClientOriginalName();
    $req->image_name->move('uploads', $upload_image_name); 
    $post->image_name = $upload_image_name;
}           
$post->save();

If image is required - add validation in action beginning - but right way for it - make validation inForm Request

$request->validate([
    'image_name' => 'required|image',
    'title'      => 'required|string'
]);

If image is not required - change your migration and make posts.image_name nullable

I use following code but I don't think this is conventional way. Here is the code:

if($req->hasFile('image_name')){
    $upload_image_name = time().'_'.$req->image_name->getClientOriginalName();
    $req->image_name->move('uploads', $upload_image_name);        
    }
    else
    $upload_image_name = "Noimage";

   $post = new Post;
    $post->title = $req->input('title');       
    $post->image_name = $upload_image_name;
    $post->save();

As I used my last laravel project.

$image = $request->file('thumbnail');
    if (isset($image)) {
        $imageName = date('y_m_d') . "_" . uniqid().".".$image->getClientOriginalExtension();
        if (!Storage::disk('public')->exists('thumbnail')) {
            Storage::disk('public')->makeDirectory('thumbnail');
        }
        $postImage = Image::make($image)->stream();
        Storage::disk('public')->put('thumbnail/' . $imageName, $postImage);
    } else {
        $imageName = "";
    }


$post = new Post;
$post->title = $request->title;
$post->image_name = $imageName;
$post->save();

image_name column should be nullable.

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