Deshola's avatar

File Uploading!

Hi, Please, I need a bit of help with file uploading. This is what I am trying to achieve with my snippet of code of file uploading:

  1. Saving the photo in a directory (seems problematic).
  2. Saving the photo's link in the database (solved, but i welcome you suggestion if there is a better way). Below is my code:

public function store(BlogRequest $request) {
        $request = $request->all();
        $request['picture'] = "/pictureStorage/" . $request['picture'];
        Blog::create($request);

// The issue part $name = $request->file('picture')->getClientOriginalName(); if($request->file('picture')->move('pictureStorage/ourFile', $name)){ return 'File was moved.'. 'you are now in'.URL::previous(); }else{ return "Something horrible went wrong!"; } }

0 likes
9 replies
Deshola's avatar

Thank you, @habeebnet.

I have modified my code to:


        $request = $request->all();
        $request['picture'] = "/pictureStorage/" . $request['picture'];
        Blog::create($request);
        if($request->hasFile('picture')){
            $request->file('picture')->store('images');
        }else{
            return "file not found";
        }

Actually, the error I am receiving is : "Call to a member function hasFile('picture') on array". I understand that I may be calling the method the wrong way, so what is the correct way? Thank you.

InaniELHoussain's avatar
$req = $request;
$request = $request->all();
    $request['picture'] = "/pictureStorage/" . $request['picture'];
    Blog::create($request);
    if($req ->hasFile('picture')){
        $req ->file('picture')->store('images');
    }else{
        return "file not found";
    }
WebKenth's avatar

Consider using the Storage Facade for storing your files, this will ensure they land where you want them to and you can catch any unwanted exceptions

Also consider uploading the images in a separate call than creating your Blog this will allow you to validate the image before creating the Blog and when you finally create the blog, all you need to do is attach the id/path of the image.

1 like
WebKenth's avatar

Change your db table column name 'picture' to 'picture_file' Not tested.. but this should work

.. What? the database has nothing to do with the file field

if you want to access $request->picture then your input must have name="picture". It has nothing to do with the database

Deshola's avatar

@habeebnet , Yes, I got your point. Actually, I am not a beginner in PHP programing, but Laravel. I am aware of the best practice, the snippet of code is just to try something out....like, the bigger picture is hidden. Thank you for the input.

Please or to participate in this conversation.