upload multiple images using laravel API : with polymorphic relation - php

I'm building an API with Laravel 8 and I have posts and images table with polymorphic relation
So I want to upload multiple images and I'm doing it in postman, And when I upload images and enter posts fields with values, like this:
as you can see, I have an error in my foreach($files as $file)
ErrorException: Invalid argument supplied for foreach()
(In headers part Content-Type has multipart/form-data value )
So I think my problem is in store() method in postController ,
The codes :
post tables :
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->longText('body');
$table->string('video')->nullable();
$table->string('study_time');
$table->integer('likes')->nullable();
$table->tinyInteger('status')->nullable()->comment('status is 1 when a post is active and it is 0 otherwise.')->nullable();
$table->text('tags')->nullable();
$table->foreign('category_id')->references('id')->on('categories');
$table->foreign('user_id')->references('id')->on('users');
});
and my image table :
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->integer('imageable_id');
$table->string('imageable_type');
$table->string('url');
$table->timestamps();
});
and the post model :
.
.
.
.
public function image(){
return $this->morphOne(Image::class , 'imageable');
}
and my image model :
protected $fillable = [
'url'
];
public function imageable(){
return $this->morphTo();
}
and my store() method in postController :
public function store(Request $request )
{
$post = new Post;
$post->category_id = $request->get('category_id');
$post->title = $request->get('title');
$post->body = $request->get('body');
$post->study_time = $request->get('study_time');
$post->tags = $request->get('tags');
$post->user_id = JWTAuth::user()->id;
$tags = explode(",", $request->tags);
$post->tag($tags);
$allowedfileExtension=['pdf','jpg','png'];
$files = $request->file('fileName');
foreach ($files as $file) {
$extension = $file->getClientOriginalExtension();
$check = in_array($extension, $allowedfileExtension);
if($check) {
foreach($request->fileName as $mediaFiles) {
$url = $mediaFiles->store('public/images');
//store image file into directory and db
$image = new Image();
$image->url = $url;
}
}
else {
return response()->json(['invalid_file_format'], 422);
}
}
$post->image()->save($image);
$post->save();
return response()->json($post , 201);
}
thank you for your help :}

$files = $request->file('fileName');
... is returning null in your case, done you are not posting fileName, you use url.
If you would have validated your incoming data you would have received a validation errors 6 because of this. So: always validate incoming d data. Not only to catch errors like this, also b for security reasons.

public function store(Request $request)
{
if ($this->getErrorIfAny($request->all(), $this->ruls)) {
return $this->getErrorIfAny($request->all(), $this->ruls);
}
if (!$request->hasFile('image_url')) {
return response($this->getResponseFail(trans('my_keywords.uploadFileNotFound'), false), 400);
}
$allowedfileExtension = ['jpg', 'png', 'jpeg'];
$files = $request->file('image_url');
$number_photos_upload = count($files);
$pictures_available_upload = array();
for ($i = 0; $i < count($files); $i++) {
$extension = $files[$i]->getClientOriginalExtension();
$check = in_array($extension, $allowedfileExtension);
if ($check) {
$pictures_available_upload[$i] = $files[$i];
}
}
$number_images_success_uploded = 0;
$images_urls = array();
for ($i = 0; $i < count($pictures_available_upload); $i++) {
$image = $pictures_available_upload[$i];
$path = config('paths.storage_path') .
$image->store(config('paths.store_image_path'), 'public');
//store image file into directory and db
$store_images = new StoreImages();
$store_images['store_id'] = $request['store_id'];
$store_images['image_url'] = $path;
$result = $store_images->save();
if ($result) {
$images_urls[$i] = $path;
$number_images_success_uploded = $number_images_success_uploded + 1;
}
}
if ($number_images_success_uploded == 0) {
return response($this->getResponseFail(trans('my_keywords.invalidFileFormat'), false), 422);
} else {
$data = [
'store_id' => (int) $request['store_id'],
'number_photos_upload' => $number_photos_upload,
'number_images_success_uploded' => $number_images_success_uploded,
'images' => $images_urls,
];
return response($this->getResponse(__('my_keywords.operationSuccessfully'), true, $data), 200);
}
}

Related

How to keep default image when updating a record in Laravel

When a user updates a movie record and uploads a new image I want an older image to be deleted and a new one to be uploaded but if a movie has a default image I don't want to delete it (because other records with the default image won't have any after that) and just upload a new one during an update. And if a user doesn't upload anything then just keep a record with a default image like before while other parameters are getting updated. My code has some errors so here is the update function:
public function update(StoreMovieRequest $request, Movie $movie)
{
$input = $request->all();
if ($image = $request->file('image_path') || $movie->image_path != 'images/default.png') {
$deleteImage = unlink(public_path(). '/' . $movie->image_path);
$image = $request->file('image_path');
$imageDestinationPath = 'images/';
$movieImage = $imageDestinationPath . date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($imageDestinationPath, $movieImage);
$input['image_path'] = "$movieImage";
} elseif($image = $request->file('image_path') || $movie->image_path == 'images/default.png') {
$image = $request->file('image_path');
$imageDestinationPath = 'images/';
$movieImage = $imageDestinationPath . date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($imageDestinationPath, $movieImage);
$input['image_path'] = "$movieImage";
}
$movie->update($input);
}
My migration:
public function up()
{
Schema::create('movies', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('status')->nullable()->default(0);
$table->string('image_path')->default('images/default.png');
});
}
Model:
public $timestamps = false;
protected $fillable = ['name', 'status', 'image_path'];
Request:
public function rules()
{
return [
'name' => 'required',
'image_path' => 'image',
];
}

Replace image when update in Laravel 8 [duplicate]

This question already has an answer here:
Fetch image variable and display on input file
(1 answer)
Closed 11 months ago.
Both function are same and the store function are running perfectly but update function have some errors
public function store(Request $request)
{
$employee = new Employee;
$employee->phone = $request->emp_num;
$employee->name = $request->emp_name;
$employee->email = $request->emp_email;
$employee->address = $request->emp_add;
if ($request->has('emp_image')) {
$image = $request->file('emp_image');
$filename = $image->getClientOriginalName();
$savePath = env('UPLOAD_PATH');
$image->move($savePath, $filename);
$employee->image = $request->file('emp_image');
}
$employee->save();
return redirect()->route('employee.index')
->with('success','Employee has been created successfully.');
}
public function update(Request $request, employee $employee)
{
$employee->name = $request->emp_name;
$employee->email = $request->emp_email;
$employee->phone = $request->emp_num;
$employee->address = $request->emp_add;
if ($request->has('emp_img')) {
$image = $request->file('emp_img');
$filename = $image->getClientOriginalName();
$savePath = env('UPLOAD_PATH');
$image->move($savePath, $filename);
$employee->image = $request->file('emp_img');
}
$employee->update();
return "Updated";
return redirect()->route('employee.index')
->with('success', $request->emp_name.' Employee data has been Updated successfully.');
}
The error
Call to a member function getClientOriginalName() on null
To store data with image
public function store(Request $request)
{
$category = new Category();
$imageName = time().'.'.$request->image->extension();
$imageName = $request->file('image')
->storeAs('images/category_photo', $imageName, 'public');
$category->name = $request->name;
$category->image = $imageName;
$category->save();
if ($category) {
return redirect()->route('category.index')
->with('success', 'Category Added Successfully');
}
}
To edit data with images and delete the existing image
public function update(Request $request, Category $category)
{
$category->name = $request->name;
if ($request->file('image')) {
$imageName = time().'.'.$request->image->extension();
Storage::delete('public/'.$category->image);
$category->image = $request->file('image')
->storeAs('images/category_photo', $imageName, 'public');
}
$save = $category->save();
if ($save) {
return redirect()->route('category.index')
->with('success', 'Category Updated Successfully');
}
}

Multiple images deleted from database but not from disc Laravel 7

I am working with Laravel 7 trying to delete multiple images from my app. When I hit the delete button, the images are removed successfully from the show.blade.php as well as from the database. However, they are still in my storage on my local disk. I am storing my images in storage/app/public/upload as well as the symlink pointing to storage/upload in the public directory under app. I have tried a variety of ways to get it to delete but nothing has been fruitful. I have my one to many relationships set up in my models which I will show below. I need this to work under three circumstances such as if there is no image, one image or many images. I am using Laravel Resources for my routing and so my TaskController.php only has one destroy method.
Here is the code I have so far:
Models -
Image.php (relevant functions only - Storage and Task classes imported at top)
public function task()
{
return $this->belongsTo('App\Task', 'task_id');
// return $this->belongsTo(Task::class);
}
public static function boot()
{
parent::boot();
self::deleting(function ($images) {
Storage::delete(Storage::path($images['name']));
});
}
Task.php (relevant code only - Storage, File and Image classes imported at top)
public function images()
{
// return $this->hasMany('App\Image');
return $this->hasMany(Image::class);
}
public static function boot()
{
parent::boot();
self::deleting(function ($task) {
foreach ($task->images ?: [] as $image) {
$image->delete();
}
});
}
Controller
TasksController.php (store, show, update and destroy)
public function store(Request $request)
{
$this->validate($request, [
'task_name' => 'required',
'task_description' => 'required',
]);
// Create Task
$user = Auth::user();
$task = new Task();
$data = $request->all();
$task->user_id = $user->id;
$task = $user->task()->create($data);
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach ($files ?: [] as $file) {
$name = time() . '-' . $file->getClientOriginalName();
$name = str_replace(' ', '-', $name);
$file->storeAs('public/upload', $name);
$task->images()->create(['name' => $name]);
$images = new Image;
$images->name = $name;
}
}
$task->task_name = $request->input('task_name');
$task->task_description = $request->input('task_description');
$task->task_priority = $request->input('task_priority');
$task->task_assigned_by = $request->input('task_assigned_by');
$task->task_assigned_to = $request->input('task_assigned_to');
$task->task_to_be_completed_date = $request->input('task_to_be_completed_date');
$task->task_notes = $request->input('task_notes');
$task->task_status = $request->task_status;
$task->save();
return redirect('/home')->with('success', 'Task Created');
}
public function update(Request $request, $id)
{
$this->validate($request, [
'task_name' => 'required',
'task_description' => 'required',
]);
$task = Task::find($id);
$task->task_name = $request->input('task_name');
$task->task_description = $request->input('task_description');
$task->task_priority = $request->input('task_priority');
$task->task_assigned_by = $request->input('task_assigned_by');
$task->task_assigned_to = $request->input('task_assigned_to');
$task->task_to_be_completed_date = $request->input('task_to_be_completed_date');
$task->task_notes = $request->input('task_notes');
$task->task_status = $request->input('task_status');
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach ($files ?: [] as $file) {
$name = time() . '-' . $file->getClientOriginalName();
$name = str_replace(' ', '-', $name);
$file->storeAs('public/upload', $name);
$task->images()->create(['name' => $name]);
$images = new Image;
$images->name = $name;
}
}
$task->save();
return redirect('/home')->with('success', 'Task Updated');
}
public function show($id)
{
$task = Task::find($id);
return view('tasks.show')->with('task', $task);
}
public function destroy($id)
{
$task = Task::findOrFail($id);
$images = Image::find($id);
$images = explode(',', $images['name']);
foreach ($images as $image) {
// $path = 'storage/app/public/upload/' . $image;
if (file_exists('../storage/app/public/upload/' . json_decode($image, true)['name'])) {
// print_r('file found');
// unlink('../storage/app/public/upload/' . base64_decode($image, true)['name']);
// dd('../storage/app/public/upload/' . json_decode($image, true)['name']);
// File::delete('../storage/app/public/upload/' . json_decode($image, true)['name']);
dd('../storage/app/public/upload/' . $task['image']);
File::delete('../storage/app/public/upload/' . json_decode($image, true)['name'] . $task['images']);
} else {
print_r('no sirve ' . __DIR__ . ' ' . $image . var_dump($image));
}
// dd($path);
// if (File::exists($path)) {
// File::delete($path);
// }
}
// $task->delete();
return redirect('home')->with('success', 'Task Deleted');
}
I have left some commented code included so you can see what I have tried. If I am missing anything, please let me know and I will edit my question.
Thank you in advance for your help. I have been stuck on this for a week.
EDIT
I have changed my destroy function. It still does not delete the files from the disk. Here is the function:
public function destroy($id)
{
// $task = Task::findOrFail($id);
$task = Task::with('images')->findOrFail($id);
// $images = Image::find($id);
// $images = $task->images($id)->get();
foreach ($task->images as $image) {
// dd(storage_path('app/public/upload/' . $image['name']));
Storage::delete(storage_path('app/public/upload/' . $image->name));
}
$task->images()->delete();
$task->delete();
return redirect('home')->with('success', 'Task Deleted');
}
I ended up calling the public folder for the delete function using Storage::disk('public')->delete('upload/' . $image->name);
That in the end helped me to delete the files from my disk. I hope this helps anyone who faces the same issue. Thank you Alzafan Christian for your help in this. You led me in the right direction.

Problem with CRUD(update) Upload File "call to a member function getClientOriginalName() on null"

I want to Update an image using Laravel storage file system in my admin data. However, there's an error when I attempt to upload an image
Iam using Laravel 5.7
Here is my create, the create is success
public function store(Request $request)
{
//
$product = new \App\Product;
$product->product_name = $request->get('product_name');
$product->desc = $request->get('desc');
$product->stock = $request->get('stock');
$product->price = $request->get('price');
$product->category = $request->get('category');
$img = $request->file('img');
$new_name = rand() . '.' . $img->getClientOriginalExtension();
$img->move(public_path('img'), $new_name);
$product->img = $new_name;
$product->save();
return redirect('admin')->with('success', 'Data Produk telah ditambahkan');
}
Here is my update
public function update(Request $request, $id)
{
//
$product = $request->all();
$product= \App\Product::find($id);
$new_name = $request->file('img')->getClientOriginalName();
$destinationPath = 'img/';
$proses = $request->file('img')->move($destinationPath, $new_name);
if($request->hasFile('img'))
{
$product = array(
'product_name' => $product['product_name'],
'desc'=> $product['desc'],
'stock'=> $product['stock'],
'price'=> $product['price'],
'category'=> $product['category'],
'img' => $new_name,
);
$product->save() ;
return redirect('admin')->with('success', 'Data Produk telah ditambahkan');
}
}
Call to a member function getClientOriginalName() on null
I think there is no image file attach while updating. You can use my code as reference.
Don't forget to check for the input field in your update field.
First check if there is image file or not. Then, go for getting name, extension and other staff.
public function update($id, Request $request)
{
$input = $request->all();
$product= \App\Product::find($id);
if (empty($product)) {
Flash::error('product not found');
return redirect(route('products.index'));
}
if ($request->hasFile('product_img')) {
$fileNameWithExt = $request->file('product_img')->getClientOriginalName();
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extension = $request->file('product_img')->getClientOriginalExtension();
$new_product_img = $filename . '_' . time() . '.' . $extension;
$path = $request->file('product_img')->move('images/products', $new_product_img);
Storage::delete('products/'.$product->product_img);
$input['product_img']= $new_product_img;
}
$product= $this->productRepository->update($input, $id);
Flash::success('product updated successfully.');
return redirect(route('products.index'));
}

Add a limit to users creating a item

I am using laravel for a project i am making.
So i want that users can only create 30 products, and if they have more then 30 products, they cant create more products until they have removed some. What do i have to add in my code so that they cant add more products.
My Product controller
public function store(Request $request)
{
//check if user has more then 30 products
$product = Product::create($request->all());
$productPhotos = [];
$photos = $request->post('photo');
if (count($photos) <= 5) {
foreach (range(1, $photos) as $i) {
foreach ($photos as $imageData) {
$bcheck = explode(';', $imageData);
if (count($bcheck) > 1) {
list($type, $imageData) = explode(';', $imageData);
list(, $extension) = explode('/', $type);
list(, $imageData) = explode(',', $imageData);
$fileName = uniqid() . '.' . $extension;
$imageData = base64_decode($imageData);
Storage::put("public/products/$fileName", $imageData);
$imagePath = ('storage/products/' . $fileName);
$productPhotos[] = ProductPhoto::create([
'product_id' => $product->id,
'path' => $imagePath
]);
}
}
}
} else {
return response()->json("You cant add any photo's to your product", 400);
}
return response()->json([$product, $productPhotos], 201);
}
if i need to send some more code, let me know.
Thx in advance.
FINAL CODE:
$totalProduct = Product::where('supplier_id', $request->user()->Supplier->id)->count();
if ($totalProduct < 30){
$product = Product::create($request->all());
$productPhotos = [];
$photos = $request->post('photo');
if (count($photos)) {
foreach ($photos as $i => $imageData) {
if ($i >= 5) {
continue;
}
$bcheck = explode(';', $imageData);
if (count($bcheck) > 1) {
list($type, $imageData) = explode(';', $imageData);
list(, $extension) = explode('/', $type);
list(, $imageData) = explode(',', $imageData);
$fileName = uniqid() . '.' . $extension;
$imageData = base64_decode($imageData);
Storage::put("public/products/$fileName", $imageData);
$imagePath = ('storage/products/' . $fileName);
$productPhotos[] = ProductPhoto::create([
'product_id' => $product->id,
'path' => $imagePath
]);
}
}
}
return response()->json([$product, $productPhotos], 201);
} else{
return response()->json("you have to much products", 201);
}
}
User Model
public function projects()
{
return $this->hasMany('App\Project', 'id', 'user_id');
}
Project Model
public function users()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
Controller to Add projects
public function store(Request $request)
{
$totalCreatedProjects = $request->user()->products->count();
if ($totalCreatedProjects < 30) {
`Your code to add projects here`
}
`Your code to alert maximum projects achieved here`
}
This example assumed:
1. Your users are authenticated;
2. You created a database relationship 1 to many between Projects and Users;
Notes: When you compare to the amount of projects that exist and the number you wish to hold the creation instead of proceeding, this should be a service.
The number should be a constant with a proper semantic so other developers understand what you are trying to achieve
You can use this:
public function store(Request $request)
{
if($request->user()->products->count() < 30) {
//Add product
...
}else{
return redirect()->back();
}
}
public function store(Request $request)
{
//check if user has more then 29 products
if ($request->user()->products->count() >= 30) {
return response()->json("You cant add more then 30 products", 400);
}
// Your code...
In User Model Add
public function canAddNewProduct()
{
return $this->products->count() < 30;
}
In Controller
Auth::guard('web')->user()->canAddNewProduct()
Better way of doing is make a new middleware and use
return Auth::guard('web')->user()->canAddNewProduct() ? true : false
to protect the routes

Categories