Webiondev123's avatar

Unable to upload image in RegisterController.php

public function uploadfile(){

        $rules = array(
            'file' => 'required | mimes:jpeg,jpg,png | max:1000',
        );


        $request=new Request();
        $validator = Validator::make($request->all(), $rules);
            
            if ($validator->fails()) {
                return Redirect::back()
                    ->withErrors($validator)
                    ->withInput();
            }

            $file = $this->$request->file('file')->store('public');

            return $file;


    }
    protected function create(array $data)
    {

        $file=self::uploadfile();
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'city'=> $data['city'],
            'country'=>$data['country'],
            'type'=>$data['type'],
            'file'=>$data['file']
            
        ]);
    }

Uploading a file like php7AEB.tmp

0 likes
7 replies
lostdreamer_nl's avatar
        $file=self::uploadfile();

That wont work.... you're trying to call the method statically

public function uploadfile(){ ... }

But it was not created statically.

Also:

if ($validator->fails()) {
                return Redirect::back()
                    ->withErrors($validator)
                    ->withInput();
            }

This could return a redirect instead of an uploaded file But you are not checking, after the upload, to see if the upload succeeded or that you got a redirectResponse returned.

        $file=self::uploadfile();

Then again. the create() method is private, so you're calling that one from somewhere else as well (probably also not checking the outcome)

And last:

$request=new Request();

Gives you an empty request object instead of the current request object. so it would never validate.

This might work.... but there might be more bugs:


public function uploadfile(){

        $rules = array(
            'file' => 'required | mimes:jpeg,jpg,png | max:1000',
        );


        // creating a new Request gives you an empty request object... not much good
//        $request=new Request();
        $request= \Request::capture();  // This gives you the current request
        $validator = Validator::make($request->all(), $rules);
            
            if ($validator->fails()) {
        // Throwing an exception will bubble up to where it can be handled
                Throw new HttpResponseException( Redirect::back()
            ->withErrors($validator)
            ->withInput() );
            }

            $file = $this->$request->file('file')->store('public');

            return $file;


    }
    protected function create(array $data)
    {

        $file=$this->uploadfile(); // Use $this->  instead of self::
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'city'=> $data['city'],
            'country'=>$data['country'],
            'type'=>$data['type'],
            'file'=>$data['file']
            
        ]);
    }

Now from the part where you call $this->create($data); you can replace it with:

Try {
    $this->create($data);
} catch (HttpResponseException $e) {
    // grab the underlying response from the exception and return it to the user
    return $e->getResponse();
}
Webiondev123's avatar

The image is uploaded in Storage/app/public but in database this file is uploaded

c:/xxx/xxx/php62EA.tmp

lostdreamer_nl's avatar
Level 53

In that case, just make sure you save the correct path to the DB:

        $file=$this->uploadfile(); // Use $this->  instead of self::
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'city'=> $data['city'],
            'country'=>$data['country'],
            'type'=>$data['type'],
            'file'=>$file   // This is the actual path after store() has done it's work
        ]);

Just remember, with your code as it is now, $file could also be a redirectResponse instead of a filepath, which would break the User::create() command.

You might want to check into the other changes I proposed because right now you're not checking anything (I'm even amazed that it somehow passes the validation in uploadFile() when you're validating a newly created empty Request object)

elvinmejia's avatar

I have the same problem

This is my Controller: ProductController.php

public function store(StoreRequest $request, Product $product){

    $product = $product->store($request);
    return back()->with('flash', 'El producto ha sido creado satisfactoriamente');

}

This is my Model: Product.php

public function uploadfile($request){

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

        //Get filename with the extension
        $filenamewithExt = $request->file('img')->getClientOriginalName();

        //Get just filename
        $filename = pathinfo($filenamewithExt,PATHINFO_FILENAME);

        //Get just ext
        $extension = $request->file('img')->guessClientExtension();

        //FileName to store
        $fileNameToStore = str_slug($request->name, '-').'.'.$extension;

        //Upload Image
        $path = $request->file('img')->storeAs('public/image/product',$fileNameToStore);

    } else{

        $fileNameToStore="";
    }

    return $fileNameToStore;

}

public function store($request)
{
    $url = str_slug($request->name, '-');

    $img = $this->uploadfile($request);

    return self::create($request->all() + [

        'url'   => $url,
        'img'   => $img,
        'stock' => 0,
        'state' => 1,

    ]);

}

and in the image field it is saved as a temporary file: C:\Users\elvin\AppData\Local\Temp\phpDB88.tmp

cookie_good's avatar

I'm not an authority on this, but I've had problems in the past with saving things outside of the app root directory. Don't remember the name of the Laravel facade off the top of my head, but you should able to upload directly to your app folder somewhere.

Please or to participate in this conversation.