laravel-5.8:Invalid argument supplied for foreach() - laravel

hi I make a form to upload pics in Laravel but when I open the form then it shows error: Invalid argument supplied for foreach()
blade file:
<form method="POST" action="{{ route('admin.product.alternateimages') }}" enctype="multipart/form-data" class="add-new-post">
#csrf
<strong class="text-muted d-block mb-2 mt-5">Upload Product Image</strong>
<div class="input-group mb-3">
<div class="input-group input-group-seamless">
<input type="file" name="product_alt_img[]" class="form-control mb-2 btn btn-sm btn-outline-primary mr-1 #error('product_image') is-invalid #enderror" value="{{ old('product_image') }}" id="" placeholder=""> </div>
#error('product_image')
<div class="small text-danger">{{ $message }}</div>
#enderror
</div>
</form>
function:
public function alternateimages(Request $request)
{
$altimgs = new Product;
$altimgs->product_id = $request->product_id;
$files = $request->file('product_alt_img');
foreach ($files as $file) {
$images = $file->getClientOriginalName();
$file->move(public_path('images/backend_images/product_images'), $images);
$altimgs->product_alt_img = $images;
}
$altimgs->save();
return redirect()->back()->with('flash_message_success', 'Product Images has been added successfully');
}

You may have to change product_alt_img[] to product_alt_img if you are uploading a single file.
<input type="file" name="product_alt_img" class="form-control mb-2 btn btn-sm btn-outline-primary mr-1 #error('product_image') is-invalid #enderror" value="{{ old('product_image') }}" id="" placeholder="">
Else if wish to upload multiple file, you may have to modify your controller method.
public function alternateimages(Request $request)
{
$altimgs = new Product;
$altimgs->product_id = $request->product_id;
//fetch an array of product_alt_img
$files = $request->product_alt_img;
//go over each Illuminate\Http\UploadedFile instance
foreach($files as $file)
{
$image = $file->getClientOriginalName();
....
}
....
}
NB: A more eloquent solution is to have a separate table for storing products images

Related

How To Update hasMany relationship data with multiple row at a time in Laravel?

I want to update SubCategory, which has a relationship with Category as a hasMany relationship. Now I want to update both category and subcategory at a time from one form. I want to update every subcategory which belongs to the category. But I can't do that.
Here is category model:
class Category extends Model
{
use HasFactory;
protected $guarded=[];
public function subcategory(){
return $this->hasMany('App\Models\SubCategory');
}
Here is subcategory model:
class SubCategory extends Model
{
use HasFactory;
protected $guarded=[];
public function category(){
return
$this>belongsTo('App\Models\Category','category_id','id');
}
here is update function in controller:
public function categoryUpdate(Request $request,$id){
if (is_null($this->user) || !$this->user->can('categories-update')) {
abort(403, 'Sorry !! You are Unauthorized !');
}
$request->validate([
'name' => 'required|max:191',
'status' => 'required',
]);
$Category=Category::findOrFail($id);
$Category->name = $request->name;
$Category->slug = Str::slug($request->name);
$Category->status = $request->status;
$Category->updated_by=Auth::user()->id;
$Category->update();
if($request->subcategory_name !=['']){
foreach($request->subcategory_name as $subcat){
if($subcat !=''){
SubCategory::create([
'name'=>json_encode($subcat),
'slug'=>Str::slug(json_encode($subcat)),
'category_id'=>$id,
'created_by' =>Auth::user()->id,
]);
}
}
}
Alert::success('Success','Category has been updated successfully!');
return redirect()->route('category.index');
}
I don't know the code to update multiple subcategories at a time.
Here is the Html form
<form action="{{ route('category.update', $data->id) }}" method="POST">
#csrf
<div class="form-group">
<label for="" class="mb-2">Category name</label>
<input name="name" class="form-control" value="{{ $data->name }}" type="text"
#error('name') is-invalid #enderror" placeholder="Name">
#error('name')
<div class="text-danger">* {{ $message }}</div>
#enderror
</div><br>
<div class="form-group">
<label for="" class="mb-2">SubCategory name</label>
#foreach ($subcat as $sub)
<div class="d-flex w-70 justify-content between mb-2">
<input name="subcategoryname[]" id="subcategoryname" class="form-control w-50" type="text" value="{{json_decode($sub->name)}}"></input>
<button onclick="deleteSubcategory({{$sub->id}})" id="delete_subcat" class="btn btn-danger btn-sm ms-2"><i
class="fa fa-trash text-dark" style="font-size:20px;color:white!important"
aria-hidden="true"></i></button>
</div>
#endforeach
</div><br>
<div class="form-group mt-2">
<label for="" class="mb-2">Add New SubCategory</label>
<div class="subcategory w-50">
<div class="d-flex mb-2">
<input name="subcategory_name[]" class="form-control" id="name" type="text"
placeholder="Name" multiple>
<span id="add" class="btn btn-dark ms-3">+</span>
</div>
</div>
<div class="form-group mt-2">
<label for="" class="mb-2">Status</label>
<br>
<select name="status" class="form-control" style="width:40%"
#error('status') is-invalid #enderror">
<option value="">--Select Status--</option>
<option value="Active" #if ($data->status == 'Active') selected #endif>Active
</option>
<option value="Inactive" #if ($data->status == 'Inactive') selected #endif>Inactive
</option>
</select>
#error('status')
<div class="text-danger">* {{ $message }}</div>
#enderror
</div>
<div class="form-group mt-4 d-flex justify-content-between">
<button type="button" class="btn btn-secondary btn-sm"
data-bs-dismiss="modal">Cancel</button>
<input class="btn btn-primary btn-sm"type="submit" value="Update">
</div>
</form>
The create method takes array of records you want to save. So you can build an array and pass that array to the create method on the SubCategory.
if($request->subcategory_name !=['']){
$subCategories = [];
foreach($request->subcategory_name as $subcat){
if($subcat !=''){
$subCategories[] = [
'name'=>json_encode($subcat),
'slug'=>Str::slug(json_encode($subcat)),
'category_id'=>$id,
'created_by' =>Auth::user()->id,
];
}
}
SubCategory::updateOrCreate(['name', 'slug'], $subCategories);
}

Laravel : Call to a member function getClientOriginalName() on null when Update Data

I will update the data its contain image, then when I will send to update here's the error Call to a member function getClientOriginalName()
This is my Controller
public function updateBook(Request $request, $id){
$book = DB::table('books')->where('id',$id);
$old = $book->select('images');
$ChecK = 0;
$file = var_dump($request->file('images')->getClientOriginalName());
$filename = time().$file;
$path = public_path('/Uploads');
if($request->hasFile('images')){
$file = $request->file('images');
$file->move($path, $filename);
Storage::delete($old);
$ChecK = 1;
}
else {
dd('Request Hash No File!');
}
$data = [
'name'=> $request->input('bookName'),
'year'=> $request->input('tahunT'),
'author'=> $request->input('author'),
'summary'=> $request->input('Summary'),
'publisher'=> $request->input('publishers'),
'pageCount' => $request->input('pageCount'),
'readPage'=> $request->input('ReadPage'),
'finished' => '$pageCount' == '$readPage' ? true : false,
'reading' => '$readPage' > 0 ? true : false,
'updatedAt'=> new DateTime()
];
if( $ChecK == 1){
$data = ['images' => $filename];
$book->update($data);
return redirect('home')->with('status', 'update succesfully');
}
else {
$data = ['images' => $old];
$book->update($data);
return redirect('home')->with('status', 'Update with old image ');
}
}
Here is the view
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
#foreach ($toEdit as $dt)
<form class="row g-3" enctype="multipart/form-data" method="POST" action="{{ route('update', $dt->id) }}" value="PUT">
{{ csrf_field() }}
<div class="col-md-6">
<label for="bookName" class="form-label">Nama Buku:</label>
<input type="text" class="form-control" name ="bookName"id="bookName" value="{{ ($dt->name) }}">
</div>
<div class="col-md-3">
<label for="tahunT" class="form-label">Tahun Terbit : </label>
<input type="number" class="form-control" name="tahunT" id="tahunT" value="{{ ($dt->year) }}">
</div>
<div class="col-md-3">
<label for="author" class="form-label">Author : </label>
<input type="text" class="form-control" name="author" id="author" value="{{ ($dt->author) }}">
</div>
<div class="col-md-6">
<label for="publishers" class="form-label">Publisher : </label>
<input type="text" class="form-control" name="publishers" id="publishers" value="{{ ($dt->publisher) }}">
</div>
<div class="col-md-3">
<label for="pageCount" class="form-label">Page Count :</label>
<input type="number" class="form-control" name="pageCount" id="pageCount" value="{{ ($dt->pageCount) }}">
</div>
<div class="col-md-3">
<label for="ReadPage" class="form-label">Read Page :</label>
<input type="number" class="form-control" name="ReadPage" id="ReadPage"value="{{ ($dt->readPage) }}">
</div>
<div class="col-12">
<label for="Summary" class="form-label">Summary :</label>
<textarea class="form-control" name="Summary" id="Summary">{{ ($dt->summary) }}</textarea>
</div>
<div class="col-md-12">
<label for="images" class="form-label">Book Image :</label>
<input type="file" class="form-group" name="images">
<br>
<img src="{{ asset('Uploads/'.$dt->images) }}" widht="300px"/>
<br>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
#endforeach
</div>
Here, I will update the data, if user want to change the images, so the image will be update and if no, the images use the old one. It's rull same as the other input. But, when I try to upload the new one, the error Call to a member function getClientOriginalName() happen.
Do you have any suggestion to this? I already add the code enctype="multipart/form-data" and var_dump() but the error was same. Thank you :)
You have to check, with a condition, if your image is null or not in order to avoid this error.
Try something like :
if ( isset($request->file('images')) != null ) {
$ChecK = 0;
$file = $request->file('images')->getClientOriginalName();
$filename = time().$file;
$path = public_path('/Uploads');
}
//..
Just add a simple condition :
If($request->file('image')) {
...
$request->images->getClientOriginalNe();
.....
}

How to edit image and update in laravel

I have a table called Services, now this table has the following -
-id
-title
-body
-image
-slug
-timestamps
And in administrator, services page I created for Add, Edit, Delete it.
My problem is edit and update a image. A strange problem is that, when I change the of image to aaaaa field in the service table (database), Nothing happens. should happen. because I changed rename of image to aaaaa.
web.php
Route::resource('services', 'ServiceController');
ServiceController.php
public function edit(Service $service)
{
return view('Admin.services.edit', compact('service'));
}
public function update(Request $request, Service $service)
{
$service->title = $request->title;
$service->body = $request->body;
if($request->has('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image->move(public_path('images/services'), $filename);
$service->image = $request->file('image')->getClientOriginalName();
}
$service->update();
return redirect()->route('services.index');
}
edit.blade.php
<form class="form-horizontal" action="{{ route('services.update', $service->id) }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
{{ method_field('PATCH') }}
#include('Admin.layouts.errors')
<div class="form-group">
<label for="title">عنوان</label>
<input type="text" class="form-control" id="title" name="title" placeholder="عنوان" value="{{ $service->title ? : old('title') }}">
</div>
<div class="form-group">
<label for="body">متن</label>
<textarea class="form-control" rows="10" id="body" name="body" placeholder="متن">{{ $service->body ? : old('body') }}</textarea>
</div>
<div class="form-group">
<label for="images">تصویر</label>
<div class="custom-file">
<input type="file" class="custom-file-input" id="images" name="images">
<label class="custom-file-label" for="images">تصویر محصول</label>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">ذخیره</button>
</div>
</form>
Service.php
protected $fillable = [
'title',
'body',
'image',
'slug',
];
I even changed the controller in the update method as follows, nothing happened.
$service->save();
I think one of efficient way to edit image in laravel.
add this at top of the controller
use File;
First of get your bannerId in a variable
$bannerId = $request->banner_id;
get object of that id by find ().
$bannerData = FrontEndBanner::find($bannerId);
check if file exist and check if file already exist then delete that file else same name will inserted in imageName variable
if ($request->hasFile('banner_image')){
$image_path = public_path("/uploads/resource/".$bannerData->banner_name);
if (File::exists($image_path)) {
File::delete($image_path);
}
$bannerImage = $request->file('banner_image');
$imgName = $bannerImage->getClientOriginalName();
$destinationPath = public_path('/uploads/resource/');
$bannerImage->move($destinationPath, $imgName);
} else {
$imgName = $bannerData->banner_name;
}
$bannerData->title = $request->banner_title;
$bannerData->banner_name = $imgName;
$bannerData->save();
If anyone have issue then comment
In the html you have:
<input type="file" class="custom-file-input" id="images" name="images">
and in Controller: $request->file('image').
Replace
<input type="file" class="custom-file-input" id="images" name="images">
with
<input type="file" class="custom-file-input" id="images" name="image">

Update image in laravel won't work

I'm trying to update image in my laravel project but it won't save the image, I'm using intervention package
this is the result i use dd
Controller:
public function update(Request $request, $id)
{
//
$this->validate($request, [
'student_name'=>'required|max:50',
'lead_status'=>'required|max:50',
'lead_source'=>'required|max:50',
'avatar' =>'image',
]);
$leads = Lead::findOrFail($id);
$leads->student_name = $request->student_name;
$leads->student_nric = $request->student_nric;
$leads->gender = $request->gender;
$leads->religion = $request->religion;
$leads->race = $request->race;
$leads->date_of_birth = $request->date_of_birth;
$leads->Address = $request->Address;
$leads->last_school_attended= $request->last_school_attended;
$leads->last_grade_completed = $request->last_grade_completed;
$leads->grade_appliying = $request->grade_appliying;
if($request->hasFile('avatar')){
$image=$request->file('avatar');
$filename=time() . '.' . $image->getClientOriginalExtension();
$location=public_path('images/' .$filename);
Image::make($image)->resize(300, 300)->save($location);
$leads->image=$filename;
$leads->save();
}
else{
$leads->save();
session()->flash('notif','Application Saved Successfully');
return view('leads.edit')->with('leads', $leads);
}
}
Edit.Blade View
<div class="row">
<div class="col-sm-4 form-group">
<img src="/uploads/avatars/{{$leads->image}}" style="width:150px;height:150px;border-radius:50px;">
<form enctype="multipart/form-data" action="{{route('leads.update', $leads->id)}}" method="POST" >
{{ csrf_field() }}
{{ method_field('PUT') }}
<label> Upload Image</label>
<input type="file" name="avatar">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</div>
<div class="col-sm-12">
<h4 text-muted>CHILD'S INFORMATION</h3>
<hr>
<div class="row">
<div class="col-sm-4 form-group">
<label>FULLNAME</label>
<input class="form-control" style="text-transform: uppercase;" type="text" name="student_name" value="{{$leads->student_name}}" placeholder="Enter FULLNAME.." autocomplete="off">
</div>
Note: i will always end up null value on my image please point me to a correct tutorial if u have..
......................................................................................................................................
Add a hidden input type with your database variable in your edit blade
and put the value of your hidden input name in else condition to save.
<input type="hidden" name="old_image_name"
value="#if(isset($admin_details)){{$admin_details->image}} #endif"/>

Hidden type input value not being passed in Laravel gallery Project

I have created an album. I am trying to upload photos to the album and storing the album_id through the 'hidden' type input. When i check the source code, album_id is shown in 'value' attribute but unfortunately the value is not being passed to the query during form submission.
My create method of PhotoController which shows the form
public function create($id)
{
$albums = Album::where('id',$id)->first();
return view('admin.pages.photos',compact('albums', 'id'));
}
Here is the form.
<div class="container">
<div class="row">
<a class="btn btn-success" href="/gallery/{{$albums->slug}}">Back to Gallery</a>
<h4>Upload Photos to <strong>{{$albums-> name}}</strong> Gallery</h4>
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
<img class="thumbnail" src="/images/gallery/{{$albums->cover_pic}}" alt="{{$albums->name}}">
</div>
<div class="col-md-8">
<form class="form-horizontal" action="/photo" method="POST" enctype="multipart/form-data" >
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="col-md-8">Photo Title:</label>
<input type="text" name="photo_name" class="form-control" placeholder="Name of the Photo" value="{{ old('photo_name') }}" >
</div>
<div class="form-group">
<label class="col-md-8">Description</label>
<input type="text" name="desc" class="form-control" placeholder="Write Description" value="{{ old('desc') }}">
</div>
<div class="form-group">
<label class="col-md-8">Upload Pic</label>
<input type="file" name="photo" class="form-control" value="{{old('photo')}}" >
</div>
<input type="hidden" name="album_id" value="{{$albums->id}}">
<button type="submit" name="submit" class="btn btn-success waves-effect waves-light m-r-10">Submit</button>
</form>
and the store method
public function store(Request $request)
{
$this->validate($request, [
'photo_name'=>'required|min:3',
'desc'=>'required',
'photo'=>'required'
]);
$photo = new Photo;
$photo->album_id = $request->album_id;
$photo->photo_name = $request->photo_name;
$str = strtolower($request->photo_name);
$photo->slug = preg_replace('/\s+/', '-', $str);
if($file=$request->file('photo')){
$name = time().'.'.$file->getClientOriginalName();
$file->move('images/gallery', $name);
$photo['photo'] = $name;
}
$photo->desc = $request->desc;
$photo->save();
return redirect()->back()->with('status', 'Photo Successfully Added!');
}

Resources