Reputation: 467
I am creating a new post on Laravel. But I stuck here to upload an image and save the image path to database. My controller is
if($request->hasFile('image'))
{
$image = $request->file('image');
$filename = time() . '.'. $image->getClientOriginalExtension();
$path = public_path('images');
$imagepath = $request->image->move($path, $filename);
$post->image = $imagepath;
}
But it saves path as 'C:\xampp\tmp\php2CF9.tmp'. What is causing the error? Or are there any better approaches than this?
Upvotes: 1
Views: 19613
Reputation: 1203
1) Make sure you have added enctype="multipart/form-data"
in your form and a <input type="file">
with field name="image"
2) Create a new folder named images
in your laravel public
folder.
3) In your controller
if( $request->hasFile('image')) {
$image = $request->file('image');
$path = public_path(). '/images/';
$filename = time() . '.' . $image->getClientOriginalExtension();
$image->move($path, $filename);
$post->image = $path;
}
$post->save();
4) In your view
<img src="{{ asset('images/FILENAME.EXTENSION') }}">
Hope it's helpful.
Upvotes: 2
Reputation: 470
$imageName = time().'.'.$request->image->getClientOriginalExtension();
$request->image->move(public_path('images'), $imageName);
store into database with file name
$post->image = $imageName;
display in view
{{ URL::to('/images/'.$post->image) }}
Upvotes: 0
Reputation: 5628
You can try, It will also store the full path with file name:
if ($request->hasFile('image')) {
$filename = $request->file('image')->getClientOriginalName();
$filename = url("/images") .
"/" . uniqid() .
$request->file('image')
->getClientOriginalName();
$destinationPath = "images";
$request->file('image')->move($destinationPath, $filename);
$post->image = $filename;
}
Upvotes: 0
Reputation: 177
You can try this. Whats the point of saving path to DB? U can access to your images by having filename and his extension
if($request->hasFile('image'))
{
$fileNameExt = $request->file('image')->getClientOriginalName();
$fileName = pathinfo($fileNameExt, PATHINFO_FILENAME);
$fileExt = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$fileExt;
$pathToStore = $request->file('image')->storeAs('public/images',$fileNameToStore);
}
$post = new Post;
if($request->hasFile('image')){
$post->img = $fileNameToStore;
}
$post->save();
But first u have to create a link with artisan:
php artisan storage:link
So your images will be stored in: ProjectName\storage\app\public\images
Upvotes: 1
Reputation: 27
Laravel can automaically save the correct path for you. First you need to setup the local file storage, if you haven't done so (https://laravel.com/docs/5.4/filesystem#configuration)
Then you can do fancy stuff like:
$post = new Post();
$post->image = $request->file('image')->store('image');
Upvotes: 3