So, I am trying to store an image that is uploaded through a blog post to a specific folder with its original file name.
The image is saved to the correct file path already but it's saving it as a random string name. My code is below:
public function fields(Request $request)
{
return [
ID::make('id')->sortable(),
Text::make('URL ID', 'id')->hideFromIndex(),
Text::make('Title', 'title'),
select::make('Market Type', 'market_id')->options([
'church' => 'Church',
'school' => 'School',
'business' => 'Business',
'municipal' => 'Municipal'
]),
Trix::make('Body', 'text'),
Image::make('Image', 'main_image')
->disk('blog')
->storeOriginalName('main_image')
->maxWidth(200)
->prunable(),
];
}
->storeOriginalName() is not about name of the saved file, but name of file that browser gets when clicking 'download' in the image field in detail page
Changing file names most simply can be done with ->store() method, something like this:
Image::make('Image', 'main_image')
->store(function (Request $request, $model) {
$filename = $request->main_image->getClientOriginalName();
$request->main_image->storeAs('/', $filename, 'blog');
return [
'main_image' => '/' . $filename,
'main_image_name' => $request->main_image->getClientOriginalName()
];
})
->maxWidth(200)
->storeOriginalName('main_image_name')
->prunable(),
Related
My database fields looks like this(keep in mind that i'm using a laravel migration as an example):
$table->id();
$table->string('name');
$table->string('genre');
$table->longText('image')->nullable();
$table->timestamps();
When the user store something, i run this command in my controller file(The 'image' field is optional, that's why it is not present in validate():
public function store(Request $request){
$formFields = $request->validate([
'name' => ['required', Rule::unique('game', 'name')],
'genre' => 'required',
'submitGame' => 'required'
]);
//unset($formFields['submitGame']);
//game image
if($request->hasFile('image')){
$image = $request->file('image')->store('gamePoster', 'public');
}
$insert = [
'name' => $formFields['name'],
'genre' => $formFields['genre'],
'image' => $image
];
//storing in database
Game::create($insert);
The image is being uploaded to my folder succesfully, the problem is that somehow the 'image' field does'nt go to the database.
it is really confusing, since the command
$image = $request->file('image')->store('gamePoster', 'public');
actually returns a string, i already checked it multiple times. The $image variable(unless the user did not upload any file at all) is never empty.
I am facing an error while showing back image stored in storage folder in laravel.
so here is my code of storing image in storage folder :
public function store(Request $request)
{
$data = $request->all();
// dd($request->Image);
$User = Auth::user()->id;
$rules = array(
'postname' => 'required' ,
'description' =>'required',
'Image' => 'required|image|mimes:jpeg,png,jpg|max:8192',
);
$validate=Validator::make($data,$rules);
if ($validate->fails()) {
return redirect()->back()->withInput()->withErrors($validate);
}
else{
$path = Storage::disk('local')->put('public',$request->file('Image'));
$form_data = array(
'title' => $data['postname'],
'description' => $data['description'],
'Image' => $path,
'user_id' => $User,
);
// dd($form_data);
$Posts = Post::create($form_data);
$Message = "successfully added";
return redirect('/Admin/Posts')->with('success',$Message);
}
}
and here is the blade file for retreiving image :
<img class="card-img-bottom" src="{{ Storage::url($Posts->Image)}}" width="200" height="450">
here is the link in config/filesystems.php
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
and here is the view of my table where data has been stored :
enter image description here
and its been showing in storage/app/images folder , but when I am trying to get it back from public/storage , their is no photo.
I have made the storage link of that??
now how to fetch it from the database??
here is the view method of it:
public function index(Request $request)
{
$Post = Post::get();
// dd($Post);
$User = User::get();
return view('Posts.index',compact('Post'));
}
and here is the inspect of image in browser:
<img src="/storage/1dTAYokONfbLXS74vEcus665uBhPBzVDAe53QMkL.jpg" width="200" height="450" class="card-img-bottom">
and here it the ui of image not being rendered on blade:
enter image description here
and from laravel documentation :I have done
php artisan storage:link
here is the storage folder of it:
enter image description here
and here is the public folder with subfolder called storage folder,where the files can be seen by user for fetching in blade..
:
enter image description here
any help ? how to solve it??
error solved,
what I did is, followed this stackoverflow answer:enter link description here
and my link got worked again.
I just removed the storage folder from the public folder and and again run the command
php artisan storage:link
and it solved my error
can someone help me with image display in laravel blade?
So this is full image URL after upload
http://webshop.local/uploads/products/1592949903recommend.png
It is supposed to be uploaded to
public/uploads/products
folder.
Here is part of code where I create product (ProductsController):
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'price' => 'required',
'description' => 'required',
'productImage' => 'required|image'
]);
$productImage = $request->productImage;
$productImage_new_name = time() . $productImage->getClientOriginalName();
$productImage->move('uploads/products' . $productImage_new_name);
Product::create([
'title' => $request->title,
'productImage' => '/uploads/products/' . $productImage_new_name,
'price' => $request->price,
'description' => $request->description
]);
return redirect()->route('products.index');
}
Also here is blade display:
<th><img src="{{ $product->productImage }}" alt="{{ $product->title }} image"></th>
And this is getting me right link because of:
public function getProductImageAttribute($productImage){
return asset($productImage);
}
in product model.
EDIT
When I upload new image it does not go into folder instead it just create new folder with the name of the image and inside it is file with name phpSOMETHING_RANDOM_HERE.tmp
If anyone else faces this problem please check this part of your code.
$productImage = $request->productImage;
$productImage_new_name = time() . $productImage->getClientOriginalName();
$productImage->move('uploads/products', $productImage_new_name);
Specifically this line:
$productImage->move('uploads/products', $productImage_new_name);
The whole time I had dot between path and variable for the name of an uploaded file.
So to fix this problem just change dot for coma.
Instead of
$productImage->move('uploads/products' . $productImage_new_name);
You need
$productImage->move('uploads/products', $productImage_new_name);
In your store method
$path = $request->productImage->store('uploads/products');
// OR if you need to give it name
$path = $request->productImage->storeAs('uploads/products', 'filename.jpg');
You can 'productImage' => $path, while creating product.
I am build a laravel 5.8 API only application and want to return the image path as path of an API resource so that it can be consumed inside an image source attribute. So this is what I have to done to achieve this.
1. I ran php artisan storgae:link command to create the symbolic link from public/storage to storage/app/public
First I store the image inside a productImages table when a new product is successfully created like this
public function store(Request $request)
{
// create & store the product
if ($product = Product::create([
'name' => $request->name,
'category' => $request->category,
'status' => $request->status,
'price' => $request->price,
'interest' => $request->interest,
])) {
// store the product image
$file = $request->file('image');
$destinationPath = "public/images/products";
$filename = 'pramopro_' . $product->name . '_' . $product->id . '.' . $file->extension();
Storage::putFileAs($destinationPath, $file, $filename);
ProductImage::create([
'product_id' => $product->id,
'name' => $filename
]);
}
// return new product
return new ProductResource($product);
}
Return the image path in the ProductResource like this
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'category' => $this->category,
'status' => $this->status,
'price' => $this->price,
'interest' => $this->interest,
'hidden' => $this->hidden,
'imageUrl' => asset('images/products/' . $this->image->name)
];
}
Testing it on my local serve I get a path like this
{
"id": 1,
"name": "dpk",
"category": "fuel",
"status": "open",
"price": 100000,
"interest": 0.2,
"hidden": 0,
"imageUrl": "http://localhost:8000/images/products/pramopro_dpk_1.jpeg"
}
When I try to view the image by putting http://localhost:8000/images/products/randomtext_1.jpeg in my browser, I get 404 not found error.
But this http://localhost:8000/storage/images/products/pramopro_dpk_1.jpeg displays the image as expected.
How should I be retrieving the image path for it to work?
the asset() function puts you in your public directory, you need to add /storage to the path of your file , try this in your toArray function
'imageUrl' => asset('storage/images/products/' . $this->image->name)
Personal note , handling media in laravel can be a headache i personally use LaravelMediaLibrary by spaite
https://github.com/spatie/laravel-medialibrary
it has really helped me and made handling media as easy as it can get especially when handling multiple media for the same model
In my form, I asked for an image to upload. Then I already validated it and it works. But the file is not stored in the uploads folder.
Here's a snippet of my ProductController:
public function store(Request $request)
{
// Validate fields
$this->validate($request, [
'product_name' => 'required',
'product_price' => 'required',
'product_desc' => 'required',
'product_img' => 'image|required'
]);
// Upload image
if($request->hasFile('image')) {
app()->make('path.public/uploads');
$image = $request->image;
$image->move('uploads', $image->getClientOriginalName());
}
/*// Save the data into database
Product::create([
'name' => $request->product_name,
'price' => $request->product_price,
'description' => $request->product_desc,
'image' => $request->image->getClientOriginalName()
]);
// Echo a session message
$request->session()->flash('msg', 'Your product has been added');
// Redirect to view page
return redirect('/products');*/
}
I already tried looking at other possible solutions but the other questions were already at storing the image in the database. I also tried checking if uploads was a directory and existed, and it is.
Can anyone please help? Thanks.
Try this: official documentation: This is how it should look in your controller:
if($request->hasFile('image')) {
$request->file('image')->store('uplodads/', 'public');
}
This would store the image in /storage/app/public/uploads by default. You can also change the public path in /config/filesystems.php. You can then access the file (if you linked the storage) with asset('storage/uploads'.$img_name).
app()->make('path.public/uploads');
I've already solved it. The variable was wrong all along. Instead of it being product_img, I placed image.
Here's the updated code:
// Validate fields
$this->validate($request, [
'product_name' => 'required',
'product_price' => 'required',
'product_desc' => 'required',
'product_img' => 'image|required'
]);
// Upload image
if($request->hasFile('product_img')) {
$image = $request->product_img;
$image->move('uploads', $image->getClientOriginalName());
}