简体   繁体   中英

Image rules always returns error in Laravel

I have an array of data as below :

array:2 [▼
  "pg_location_id" => 10
  "image_location" => "pg_images/2017/10/pg-90d7e835d382a91d1635403f17b6fa76.jpg"
]

and the rules is :

public static $rules = [
        'pg_location_id'    =>  'required|exists:pg_locations,id',
        'image_location'    =>  'required|image|max:500',
    ];

An my controller where I am trying to insert image(s) is :

if ($request->hasFile('image')) {

                for($i = 0; $i < count($request->image); $i++) {
                    if ($request->file('image')[$i]->isValid()) {
                        $fileName = 'pg-'.md5(uniqid()).'.'.$request->file('image')[$i]->getClientOriginalExtension();
                        $request->file('image')[$i]->move($destination_path, $fileName);
                        $img_data['image_location'] = 'pg_images/'.date('Y').'/'.$pg_location->id.'/'.$fileName;

                        $validator = Validator::make($img_data, PgLocationImage::$rules);
                        if ($validator->fails()) return Redirect::back()->withErrors($validator);
                        PgLocationImage::create( $img_data );
                    }
                }
            }

But it always says

The image location must be an image

for image rule you must pass file variable but you pass a simple string variable. first check in your controller, at the first line print as follow:

public function uploadImage(Request $request)
{
    dd($requesti->hasFile('image_location'));
    $rules = [];
    ......
}

If there is file then it will return true else you can't pass a file variable in request.

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