Konstruktionsplan's avatar

Upload 🆙Image

Hello friends.

I want to build a simple upload.

First I create a request file. There I define the rules.

   public function rules()
    {
        return [
            'title' => 'required',
            'link' => 'required',
            'image' => 'required',
        ];
    }

Now the controller...

public function store(StorePlatformRequest $request)
    {
        Platform::create($request->validated());

        $newImageName = time() . '-' . $request->title . '.' . $request->image->extension();
        $request->image->move(public_path('img'), $newImageName);

        return redirect()->route('dashboard');
    }

The problem is that it saves me the path "/tmp/phpVLn6qr" in the database.

It is the wrong directory, with the wrong name and without extension. What exactly am I doing wrong?

0 likes
9 replies
PaulMaxOS's avatar

I think it's because you're using the $request to create your new Platform entity. At this time the image isn't stored and resides in your /tmp folder.

So store it first and then use the stored image for your Platform::create().

1 like
Konstruktionsplan's avatar

That's what I thought at first too!

But then what comes from the view is not validated, so I discarded that.

PaulMaxOS's avatar

I don't get fully get what you mean... Something like this wouldn't work?

$validatedRequest = $request->validated();

$image = // Store your image

Platform::create([
	'title' => $validatedRequest['title‘],
	'link' => $validatedRequest['link'],
	'image' => // Whatever you did to the $image above
]);
1 like
Konstruktionsplan's avatar
    $request->validated();

        $newImageName = time() . '-' . $request->title . '.' . $request->image->extension();
        $request->image->move(public_path('img'), $newImageName);

        Platform::create($request->except('image') + [
                'image' => $request->image->storeAs('img', time() . '-' . $request->title . '.' . $request->image->extension(), 'public')
        ]);

        return redirect()->route('dashboard');

Now this error:

The "/tmp/php3yUmFF" file does not exist or is not readable.

Quite strange, since I never told it to save it to the "tmp" directory.

Konstruktionsplan's avatar

If I removed these lines, then it no longer uploads the image.

$newImageName = time() . '-' . $request->title . '.' . $request->image->extension();
	$request->image->move(public_path('img'), $newImageName);
Konstruktionsplan's avatar

Aww. Now it works!

I did read the documentation on the "public disk" but was kind of expecting it to all happen in the "public" folder. Which it doesn't. The magic happens in the storage folder and is linked with a symbolic link.

Thanks for the help!

Please or to participate in this conversation.