I need upload a image to Google storage and insert the below JSON object with the gcs image path in MongoDB.
The image is successfully getting uploaded in GCS, but I am not able to get the image url of the image and also not able to update the path in mongoDB.
JSON object format
{
"original": "/pictures/1620305924456-74535-605b8a97a02cf2c1",
"thumbnail": "/pictures/1620305924456-74535-605b8a97a02cf2c1",
"fileType": "image"
}
Can anyone help me to implement the this logic.
public function store(Request $request)
{
request()->validate([
'name' => 'required',
'imageUrl' => 'required|image|mimes:jpeg,png,jpg|max:2048',
]);
$disk = Storage::disk('gcs');
$imagePath = $request->file('imageUrl');
$imageName = $imagePath->getClientOriginalName();
$disk->put('pictures', $request->file('imageUrl'));
$player->name ='test';
$player->imageUrl = [
'original' => '/pictures/nScT0KD7LoQucnfoFBLFfNAw9pmdfPnvtyC0VHq6.jpg',
'thumbnail' => '/pictures/nScT0KD7LoQucnfoFBLFfNAw9pmdfPnvtyC0VHq6.jpg',
'fileType'=> 'image'
];
Appreciation::create($player);
return redirect()->route('appreciation.index')
->with('success','Record created successfully.');
}
Thanks in advance
Finally I fixed it using below code .
request()->validate([
'name' => 'required',
'imageUrl' => 'required|image|mimes:jpeg,png,jpg|max:2048',
]);
$appreciation = new Appreciation();
$appreciation->name = $request->get('name');
$imagePath = $request->file('imageUrl');
$imageName = $imagePath->getClientOriginalName();
$disk = Storage::disk('gcs');
$url = $disk->url('/pictures/'.$imageName);
$disk->putFileAs('/pictures/', $request->file('imageUrl'), $imageName);
$data = [
'original' =>'/pictures/'.$imageName,
'thumbnail' => '/pictures/'.$imageName,
'fileType'=> 'image'
];
$appreciation->imageUrl = $data;
$appreciation->save();
Related
can someone help me, i want to add article with image. image has successfully entered the directory but in the database the name is always D:\xampp\tmp\php......tmp.
I have changed the system file to public.
Controller
public function store(Request $request)
{
//
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
if ($request->file('thumbnail')) {
$imageName = time().'.'.$request->file('thumbnail')->getClientOriginalExtension();
$validatedData['thumbnail'] = $request->thumbnail->move(public_path('uploads/article/'), $imageName);
}
//dd($validateData['thumbnail']);
Article::create($validateData);
return redirect('/admin-article')->with('success', 'Data has been successfully added');
}
Try this
if ($request->file('thumbnail')) {
$imageName = time().'.'.$request->file('thumbnail')->getClientOriginalExtension();
$request->thumbnail->move(public_path('uploads/article/'), $imageName);
$validatedData['thumbnail'] = url('uploads/article/'.$imageName);
}
The reason why it's return a path instead of url because you're using public_path instead of url()
Controller Code
public function store(Request $request)
{
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
// Check if request has file
if($request->hasFile('thumbnail')){
// Get File
$file = $request->file('thumbnail');
// Get File Extention
$fileGetFileExtension = $file->getClientOriginalExtension();
// Create customized file name
$fileName = Str::random(20).'_'.date('d_m_Y_h_i_s').'.'.$fileGetFileExtension;
// Save File to your storage folder
Storage::disk('public')->put('uploads/article/'.$fileName,File::get($file));
}else{
$fileName = null;
}
$validatedData['thumbnail'] = $fileName;
Article::create($validateData);
return redirect('/admin-article')->with('success', 'Data has been successfully added');
}
Run php artisan storage:link, if not created
In blade you can get your file like this
I hope this helps. :D
thanks for your answer my problem has been solved with code like this, but only the name of the file stored in the database not with the name of the directory.
public function store(Request $request)
{
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
$imageName = time().'.'.$request->thumbnail->getClientOriginalExtension();
$request->thumbnail->move(public_path('articles/'), $imageName);
$Article = new Article;
$Article->title = $validateData['title'];
$Article->thumbnail = $imageName;
$Article->slug = $validateData['slug'];
$Article->description = $validateData['description'];
$Article->save();
return redirect('/admin-article')->with('success', 'Data has been successfully added');
}
So here it is.
I want to edit a data in database, it work perfectly if I upload an image every time I fill the form. but the problem raised when I edited another data and didn't upload an image instead of filling it with old image data (which is the file in my local) from database which is a string. the image validation makes the error was raised.
here my image validation
'image' => 'image|max:1024'
if I just put it like this 'image' => 'max:1024', it will run well because it wouldn't check if it's an image, but it will generate a problem where user start using edit data function to inject another unwanted code.
here is the update code
use WithFileUploads;
public $productId;
public $title;
public $description;
public $price;
public $image;
public $imageOld;
protected $listeners = [
'editProduct' => 'editProductHandler'
];
public function update()
{
$this->validate([
'title' => 'required|min:3',
'price' => 'required|numeric',
'description' => 'required|max:180',
'image' => 'image|max:1024'
]);
if ($this->productId) {
$product = Product::find($this->productId);
$image = '';
if ($this->image) {
Storage::disk('public')->delete($product->image);
$imageName = \Str::slug($this->title, '-')
. '-'
. uniqid()
. '.' . $this->image->getClientOriginalExtension();
$this->image->storeAs('public', $imageName, 'local');
$image = $imageName;
} else {
$image = $product->image;
}
$product->update([
'title' => $this->title,
'price' => $this->price,
'description' => $this->description,
'image' => $image
]);
$this->emit('productUpdated');
}
}
i'm trying to upload multiple images using laravel and so far i've succeded, but the problem is that when i try to save text AND the files i get an error.
So far i've received so many errors that i can't remember all of then, but the latest is:
SQLSTATE[HY000]: General error: 1364 Field 'title' doesn't have a default value (SQL: insert into posts (image, updated_at, created_at) values (["italian.jpg"], 2019-05-23 18:48:22, 2019-05-23 18:48:22))
i've set the sql properly, and as i said, if i remove the image upload it works, and if i remove the text fields it also work, but if i try both i doesnt.
if i remember correctly when i remove the required fields it also works.
public function store(Request $request)
{
//dd($request);
$this->validate($request, [
'title' => 'required|min:3|max:120',
'text' => 'required',
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
if($request->hasfile('image')){
foreach($request->file('image') as $image)
{
$name=$image->getClientOriginalName();
$image->move(public_path().'/images/', $name);
$data[] = $name;
}
} else{
redirect('/posts')->with('Error', 'no image');
}
$post->image=json_encode($data);
$post = Post::create($validatedData);
return redirect('/posts')->with('success', 'yay');
}
i also tried this, but it returns
Creating default object from empty value
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|min:3|max:120',
'category' => 'required|min:3|max:120',
'text' => 'required',
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if($request->hasfile('image'))
{
foreach($request->file('image') as $image)
{
$name=$image->getClientOriginalName();
$image->move(public_path().'/images/', $name);
$data[] = $name;
}
}
$post = new Post();
$post->image=json_encode($data);
$post->save();
return back()->with('success', 'Yay');
}
i figured it out, hehe. just had to remove these lines:
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
Thanks anyways.
I'm trying to store an image in my Laravel project, but I'm having an issue. The image is sucessfuly being added to the /public/images folder as its filename, but when the request hits the database, its added as /private/var/tmp/XXXXX. I've tried to set $request->file as the name, but it still posts as the var/temp.
Controller
public function store(Request $request)
{
$rules = [
// 'address' => 'required',
// 'city' => 'required',
// 'postcode' => 'required',
// 'restDesc' => 'required',
// 'telNumb' => 'required',
// 'resWebsite' => 'required',
// 'restDesc' => 'required',
// 'business_id' => 'unique:busprofiles,business_id',
];
$customMessages = ["Message"];
if ($request->hasFile('file')) {
$request->file->store('public/uploads');
$filename = $request->file->getClientOriginalName();
$filesize = $request->file->getClientSize();
$request->file = $request->file->storeAs('public/uploads', $filename);
}
$this->validate($request, $rules, $customMessages);
Busprofile::create($request->all());
return redirect()->route('business.dashboard')
->with('success', 'Profile created successfully');
}
If it helps: return $request->file returns the correct URL.
The problem is in Busprofile::create($request->all());. You do indeed get the original filename with $filename = $request->file->getClientOriginalName(); but your request stays the same.
Create the array for the database entries manually, according to your database needs.
$data = ['filename' => $request->file->getClientOriginalName(),
...,
];
and
Busprofile::create($data);
I have a post with title, texts & image. But I can't save the image path to database. Here is my code.
public function save(Request $request, Post $post)
{
$this->validate(request(),
[
'title' => 'required',
'image' => 'image|mimes:jpg,png,jpeg'
]);
if($request->hasFile('image'))
{
$file = $request->file('image');
$fileNameExt = $request->file('image')->getClientOriginalName();
$fileName = pathinfo($fileNameExt, PATHINFO_FILENAME);
$fileExt = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$fileExt;
Image::make($file)->resize(600, 600)->save( public_path('media/' . $fileNameToStore));
$post->image = $fileNameToStore;
auth()->user()->publish(
new Post(request(['title', 'text', 'image']))
);
}
return redirect ('/');
}
But it does not store image path to image column of database. Instead tmp data like C:\xampp\tmp\phpC549.tmp stored. What is wrong here?
I think you need to change the save code
auth()->user()->publish(
new Post(request(['title', 'text', 'image']))
);
to
auth()->user()->publish(
new Post([
'title'=>$request->title,
'text'=>$request->text,
])
);
since image val already set inside hasfile if condition
Sample Image path
public function addBlogCategoryPost(BlogCategoryRequest $request) {
$destinationPath = 'iamge path';
$data = [
'category_name' => $request->category_name,
'category_description' => $request->category_description,
'seo_url' => $request->seo_url,
'meta_title' => $request->meta_title,
'meta_description' => $request->meta_description,
'meta_keywords' => $request->meta_keywords,
'meta_author' => $request->meta_author,
];
if ($request->hasFile('category_image')) {
$file = $request->file('category_image');
//move iamge to folder
$fileName = str_random(30) . '.' . $file->clientExtension();
$file->move($destinationPath, $fileName);
$data['category_image'] = $fileName;
}
$addTag = BlogCategory::create($data);
if ($addTag) {
return $addTag;
}
}