Folarin's avatar

Filename not storing correctly in the database

I'm trying to upload a file but the file name doesn't save correctly in the database instead of getting something like '1500677031.jpeg' stored in the file column in the database I get this instead '/private/var/tmp/phpPw35Ox' and this causes the image to break in the view. here's my controller code:

public function store(UploadRequest $request)
{

    if ($request->hasFile('product_photo'))
    {
        $product_photo = $request->file('product_photo');
        $filename = time() . '.' . $product_photo->getClientOriginalExtension();
        Img::make($product_photo)->resize(250, 250)->save(public_path('/uploads/product_photo/') . $filename);

    }

    $new_product = $request->all();
    Products::create($new_product);

    session()->flash('message', 'Product successfully added to inventory');
    return redirect()->back();
}
0 likes
10 replies
tykus's avatar

You need to merge the newly defined $filename variable into your $request array before you create the Product, e.g.:

$new_product = $request->merge(['filename' => $filename])->all();
Folarin's avatar

@tykus I get this error when I include that line Call to a member function all() on null

AddWebContribution's avatar

I think you can try this: You should set field wise value in $new_product array like 'filename'

$new_product = array('filename'=>$filename);
Products::create($new_product);

Hope this work for you !!!

Folarin's avatar

@saurabhd thanks. but this also doesn't work. data doesn't event get persisted with this solution

tykus's avatar

Sorry, the merge method actually returns nothing (void); so it is not chainable; do this instead:

$request->merge(['filename' => $filename]);

Products::create($request->all());
Folarin's avatar

@tykus this works now except filename in the db still = '/private/var/tmp/phpiwM0dR'

tykus's avatar

What is the field on the database table?

Folarin's avatar

its product_photo in the database

Snapey's avatar
Snapey
Best Answer
Level 122

because you are passing the php temporary filename into the request instead of using the filename you created.

Just pass the parameters as an array to the create method instead of just throwing it the request->all() data

$product = Products::create([
       'column1' => $request->field1,
       'column2' => $request->field2,
       'column3' => $request->field3,
       'product_photo' => $filename,
       ]);

3 likes

Please or to participate in this conversation.