emco83's avatar

Need help with uploading file on Laravel 5.4

I have CRUD for posts. Now I want to upload files. I've followed the Laracasts video for simple upload, but I need to know how to retrieve the image.

OK, here's my code:

In PostsController the "store" method has:

public function store(Request $request)
{
  $this->validate($request, [
    'title' => 'required',
    'content' => 'required',
  ]);

  $post = new Post();
  $post->title = $request->title;
  $post->content = $request->content;
  $post->status = $request->status;
  $post->user_id = Auth::user()->id;
  $post->image = request()->file('image')->store('posts');

  $post->save();

  session()->flash('created_post', 'The post has been created');

  return redirect('/en/admin/posts');
}

When I create the post, the image is uploaded successfully into storage/app/posts/the_file_of_the_image.

As I've checked here: https://laravel.com/docs/5.4/filesystem#configuration

to display the image I have to create a symbolic link, so I've used the artisan command:

php artisan storage:link

Now I can see the new folder in storage/app/public, so I guess I have to upload the image here, but how do I do that with this?

$post->image = request()->file('image')->store('posts');

And in my view how do I display the image?

I've tried like this:

src="{{asset('storage/' . $post->image)}}"

(I've deleted the img tag here, 'cos it's not displaying in the post.)

but the path is wrong.

Any explanation will be very appreciated. Thanks.

0 likes
1 reply
emco83's avatar
emco83
OP
Best Answer
Level 1

OK, never mind, I've figured it out. :)

In my view i can get the image by using this code inside the src tag:

{{Storage::url($post->image)}}

and in my PostsController I've change the line into this:

$post->image = request()->file('image')->store('public/posts');

Please or to participate in this conversation.