Home > OS >  How to get images from array data and insert it into database
How to get images from array data and insert it into database

Time:08-05

i have this as my function in my controller

/**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\Models\User
 */
protected function create(array $data)
    {
        $config= ['table'=>'users', 'length'=>10, 'prefix'=>'ID'];
        $user_id = IdGenerator::generate($config);

        //save profile picture if added
        if($data->hasfile('profile')){

            $file = $data['profile'];
            $extension = $file->getClientOriginalExtension();
            $profile_pic = time().'.'.$extension;
            $file->move(public_path('images/user/'),$profile_pic);

        }
        $user =User::create([
            'id' => $user_id,
            'fullname' => $data['fullname'],
            'phonenumber' => $data['phonenumber'],
            // 'profile_image' => $profile_pic,
            'district_id' => $data['district_id'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        
        ]);
            BusinessModel::create([
                'user_id' =>$user_id,
                'business_name' => $data['business_name'],
                'category' => $data['category'],
                // 'tax_clearance'=> $data['tax'],
                // 'business_certificate'=> $data['cecrtificate'],
                // 'ppda'=> $data['ppda'],
                // 'other_docs'=> $data['otherdocs']
            ]);
        return($user);
    }

the commented lines contains input type of file so when i try using hasfile() am getting an error expected type object found an array.

how do i fix this and get the files from the form and inserting them into the database.

CodePudding user response:

Try adding request inside a function parameter like this, hope this will help

protected function create(request $data) 

CodePudding user response:

You are getting multiple files from your form , first check the input tag it should be like this.

name="photos[]" multiple

if you want to store multiple files.

Then in the controller

$files = $request->file('photos');

foreach($files as $file){
  //your store logic here
}
  • Related