简体   繁体   中英

Laravel - Storing multiple images in the database in Single Row

How can I store multiple images in my database in laravel ? I have this code but I cant pass any data it only passes one data.

I want to achieve this database format in my images Row

在此处输入图片说明

Controller

 public function store(Request $request)
{


   //Handle File Upload
   if($request->hasFile('city')){
    // Get FileName
    $filenameWithExt = implode(' , ',$request->file('city')->getClientOriginalName());
    //Get just filename
    $filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
    //Get just extension
    $extension =  implode(' , ',$request->file('city')->getClientOriginalExtension());
    //Filename to Store
    $fileNameToStore = $filename.'_'.time().'.'.$extension;
    //Upload Image
    $path =  implode(' , ',$request->file('city')->storeAs('public/city_image',$fileNameToStore));

}else{
    $fileNameToStore='noimage.jpg';
}

   $citi = new City;
   $citi->city =$fileNameToStore;
   $citi->save();

   return redirect('/lugar')->with('success', 'Data Inserted');
}

View

                 <td> {{Form::file('city[]')}} </td>

You will want to JSON encode them. Make that DB field as long text and when you are about to save the value to the DB do it so:

$citi->city = json_encode($fileNameToStore);

And when you want to read the value you will do it as:

json_decode($citi->city);

Now, I would advise to do an array of images and encode them, then decoding you can just do:

json_decode($obj->city, TRUE);

and you will have your array back

You should store the image in loop. city field is an array.

I modified your function. Let me know if i did any wrong.

public function store(Request $request)
{
    if($request->hasFile('city'))
    {
       $file = Input::file('city');
       foreach($file as $key => $part) 
       {
          $filename = $part->getClientOriginalName();
          $filenameWithExt = implode(' , ',$filename);
          $filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
          $extension =  implode(' , ',$part->getClientOriginalExtension());
          $fileNameToStore[$key] = $filename.'_'.time().'.'.$extension;
          $path =  implode(' , ',$part->storeAs('public/city_image',$fileNameToStore[$key]));
       }
       // converting images names array to comma separate string 
       $fileNameToStore = implode (", ", $fileNameToStore);
    }else{
       $fileNameToStore = null; // if no image found then it should be null
    }

   $citi = new City;
   $citi->city = $fileNameToStore;
   $citi->save();

   return redirect('/lugar')->with('success', 'Data Inserted');
}

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