Adrian Sauer
Adrian Sauer

Reputation: 3

Laravel: Upload picture to public/images - wrong file name

i'm trying to save an uploaded picture in the public/images directory.

public function store(Request $request)
{
    $request->validate([
        'title' => 'required',
        'description' => 'required',
        'image' => 'required|image|mimes:jpg,png,jpeg|max:5048'
    ]);
    $newImageName = uniqid() . '-' . $request->title . '.' . $request->image->extension();
    
    $request->image->move(public_path(('images'), $newImageName));
    
    Post::create([
        'title' => $request->input('title'),
        'description' => $request->input('description'),
        'slug' => SlugService::createSlug(Post::class, 'slug', $request->title),
        'image_path' => $newImageName,
        'user_id' => auth()->user()->id
    ]);

    return redirect('/blog')
    ->with('message', 'Dein Beitrag wurde erstellt.');

}

Everything works just fine - exept for the file name. It should have the name of $newImageName but it looks like 'php51F7.tmp'. Also the extension is '.tmp' and not '.png' or '.jpg'.

Thank you very much for your help!

PS: I'm an absolut beginner in Laravel, please be patient.

Upvotes: 0

Views: 598

Answers (2)

Jigneshsinh Rathod
Jigneshsinh Rathod

Reputation: 1028

It is issue of extra round bracket

Replace

$request->image->move(public_path(('images'), $newImageName));

With

$request->image->move(public_path('images'), $newImageName);

Upvotes: 1

RioSant
RioSant

Reputation: 153

You have typo in your code

public function store(Request $request)
{
    $request->validate([
        'title' => 'required',
        'description' => 'required',
        'image' => 'required|image|mimes:jpg,png,jpeg|max:5048'
    ]);
    $newImageName = uniqid() . '-' . $request->title . '.' . $request->image->extension();
    
    #Notice here, move() accepts two parameteres
    $request->image->move(public_path('images'), $newImageName);
    
    Post::create([
        'title' => $request->input('title'),
        'description' => $request->input('description'),
        'slug' => SlugService::createSlug(Post::class, 'slug', $request->title),
        'image_path' => $newImageName,
        'user_id' => auth()->user()->id
    ]);

    return redirect('/blog')
    ->with('message', 'Dein Beitrag wurde erstellt.');

}

Upvotes: 0

Related Questions