Is this a laravel bug? Getting filepath after upload

Published 5 days ago by woxene

I know how fileupload works and I know how to use it. But I found something strange today;

I get my path (and move the uploaded image) with this function: $path = $request->file('logo')->store('carrier_logo'); Which comes straight out of the laravel docs.

When I dump this variable using dd($path); the output is "carrier_logo/bHfFyYagJYG5nadKOVZjgxrRvncw4jsl7Of7PKEB.png"

Which is exactly what I want to write in my database. But when I merge this into the database something strange happens.. it changes into C:\xampp\tmp\php3C3A.tmpand I have no idea why or how this is happening..

Here is my full code:

    public
    function store(Request $request)
    {
        request()->validate([
            'name'              => 'required',
            'logo'              => 'nullable',
            'original_filename' => 'nullable',
        ]);
        
        if ($request->hasFile('logo')) {
            $path = $request->file('logo')->store('carrier_logo');
            dd($path); //outputs: "carrier_logo/bHfFyYagJYG5nadKOVZjgxrRvncw4jsl7Of7PKEB.png"
            $request->merge([
                'logo'              => $path, //outputs : C:\xampp\tmp\php3C3A.tmp
                'original_filename' => $request->file('logo')->getClientOriginalName(),
            ]);
        }
        
        Carrier::create($request->all());
        return redirect()->route('carriers.index')->with('toast', 'Carrier created successfully.');
    }
Best Answer (As Selected By woxene)
Cronix
$data = $request->all();

if ($request->hasFile('logo')) {
    $data['original_name'] = $request->file('logo')->getClientOriginalName();
    $data['path'] = $request->file('logo')->store('carrier_logo');
}

Carrier::create($data);
Snapey
Snapey
5 days ago (993,535 XP)

simple, dont try to merge into the request object.

create your Carrier and then add the path, or save the attributes individually

woxene

@Snapey Could you show me how this should be done? What is the best way to achieve this?

Cronix
Cronix
5 days ago (727,800 XP)
$data = $request->all();

if ($request->hasFile('logo')) {
    $data['original_name'] = $request->file('logo')->getClientOriginalName();
    $data['path'] = $request->file('logo')->store('carrier_logo');
}

Carrier::create($data);
Snapey
Snapey
4 days ago (993,535 XP)

Personally

public function store(Request $request)
{
    request()->validate([
        'name'              => 'required',
    ]);
    
    $carrier = new Carrier($request->all());

    if ($request->hasFile('logo')) {
        $carrier->logo = $request->file('logo')->store('carrier_logo');
        $original_filename = $request->file('logo')->getClientOriginalName();
    }

    $carrier->save();

    return redirect()->route('carriers.index')->with('toast', 'Carrier created successfully.');
}

much simpler to understand.

Please sign in or create an account to participate in this conversation.