How to filter subcategory data from parent category in Laravel8 - ajax

I want to filter subcategory data according to parent category.
I am getting all my subcategory inside all the categories. I tried many old answers from stackoverflow and youtube but not worked.
I want this filter inside my article post form.
create.article.blade.php
<form action="{{ URL::to('post-article-form') }}" method="post" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="exampleInputEmail1">Article Name <b style="color: red">*</b></label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter article title" name="articleTitle" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1"> Select Article category </label>
<select class="form-control" name="category" id="category" required>
<option value=""> Select </option>
#foreach($categories as $category)
<option value="{{ $category->id }}"> {{ $category->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail1"> Select Sub category </label>
<select class="form-control" name="subCategory" id="subCategory" required>
<option value=""> Select </option>
#foreach($subCategories as $subCategory)
<option value="{{ $subCategory->id }}"> {{ $subCategory->name }}</option>
#endforeach
</select>
</div>
I used this below script for filter but not worked.
<script>
$('#category').on('change',function(e){
console.log(e);
var cat_id = e.target.value;
//ajax
$.get('/ajax-subcat?cat_id='+cat_id, function(data){
//subcategory
$('#subCategory').empty();
$('#subCategory').append($("<option></option>").val("").html("--Select Sub Category--"));
$.each(data,function(index, subcatObj){
$('#subCategory').append('<option value="'+subcatObj.id+'">'+subcatObj.name+'</option>');
})
})
});
</script>
My web.php route
//sub category
Route::get('add-sub-category', [SubCategoryController::class, 'create']);
Route::post('post-sub-category-form', [SubCategoryController::class, 'store']);
Route::get('subcategories', [SubCategoryController::class, 'index']);
Route::get("/ajax-subcat", function (Request $request){
$cat_id = $request-> Input::get('cat_id');
$subCategories = SubCategory::where('category_id',$cat_id)->get();
return response()->json($subCategories);
});

Related

I want to get data to the dropdown by using another dropdown in the same page

I have a dropdown on my page to load districts. And I have another dropdown to load Divisions according to that selected district. The below code I have got all the divisions. But I want only the divisions according to the selected districts. How can I do?
#php
$districtAll=\App\District::all();
#endphp
<div class="row">
<label class="col-md-4 control-label" for="district">9. District</label>
<div class="col-md-8">
<select name="district">
<option type="text" class="detail-wp" value="">Select District</option>
#foreach($districtAll as $all)
<option value="{{$all->DISTRICT_ID}}">{{$all->DISTRICT}} </option>
#endforeach
</select>
</div>
</div>
<br>
#php
$getDsAll=\App\DsDivision::all();
#endphp
<div class="row">
<label class="col-md-4 control-label" for="ds_division">10. DS Division</label>
<div class="col-md-8">
<select name="ds_division" class="form-control">
<option type="text" class="detail-wp" value=""></option>
#foreach($getDsAll as $all)
<option value="{{$all->DIVISION_ID}}">{{$all->DIVISION}} </option>
#endforeach
</select>
</div>
</div>
You can do it using ajax request:
$('select[name=district]').on('change', function(){
$districtId = $(this).val();
$.get('/division/district/'+$districtId).done(function(res){
$.each(res, function (key, value) {
$('select[name=ds_division]').append(`<option value='` + value.id + `'>` + value.name +`</option>`);
});
});
to make this working you will need a route like
Route::get("/division/district/{district}", "DivisionController#getByDistrictId");
DivisionController#getByDistrictIdwill be
public function getByDistrictId($district)
{
return Division::where('district_id',$district)->get();
}
this code just to give you an idea of how you can do it.

Show phone code of a country selected in dropdown Laravel

I'm trying to show the phone code based on the country selected. Like when you try to register and while choosing a country the phone code changes at the same time.
here's my code.
<select class="form-control" name="country_id" required>
<option value selected disabled>Select Country</option>
#foreach ($countries as $country)
<option value="{{ $country->id }}" id="shop-country">{{ $country->name }}</option>
#endforeach
</select>
<div class="form-group">
<label>Phone Number</label>
#foreach ($countries as $country)
<span id="phonecode">{{ $country->phonecode }}</span>
#endforeach
</div>
First, you need to populate the select options with a custom attribute, for example, phonecode
<select id="countryList" class="form-control" name="country_id" required>
#foreach ($countries as $country)
<option phonecode="{{ $country->phonecode }}"
value="{{ $country->id }}"
id="shop-country">{{ $country->name }}
</option>
#endforeach
</select>
Remove foreach loop from pone code text.
<div class="form-group">
<label>Phone Number</label>
<span id="phonecode"></span>
</div>
Now, use Javascript to listen to change events on the select list.
<script>
let countryList = document.getElementById("countryList") //select list with id countryList
let phoneCode = document.getElementById('phonecode') //span with id phonecode
countryList.addEventListener('change', function(){
phoneCode.textContent = this.options[this.selectedIndex].getAttribute("phonecode");
});
</script>

Laravel: Array to string conversion Error message

I'm trying to make search function and having problem. I have Array to string conversion error message.
Could you teach me right code please?
Here is this program usage
1.User select value then click [search] button (This is search.blade.php)
2.Search result will display at result.blade.php
my Laravel Framework is 6.18.8
search.blade.php
<form action="{{ route('search') }}" class="form-image-upload" method="POST" enctype="multipart/form-data">
{!! csrf_field() !!}
<div class="col-md-5">
<strong>TYPE</strong>
<select name="type" class="form-control">
<option value="-" selected>-</option>
<option value="j">j</option>
<option value="w">w</option>
</select>
</div>
<div class="col-md-5">
<strong>wc</strong>
<select name="wc" class="form-control">
<option value="N0" selected>0</option>
<option value="N1">1</option>
<option value="N2">2</option>
<option value="N3">3</option>
</select>
</div>
<div class="col-md-5">
<strong>FC</strong>
<select name="fc" class="form-control">
<option value="0" selected>0</option>
<option value="f01">f01</option>
<option value="f02">f02</option>
<option value="f03">f03</option>
</select>
</div>
<div class="col-md-5">
<strong>YC</strong>
<select name="yc" class="form-control">
<option value="0" selected>0</option>
<option value="yc1">yc1</option>
<option value="yc2">yc2</option>
</select>
</div>
<div class="col-md-5">
<strong>SC</strong>
<select name="sc" class="form-control">
<option value="Z01" selected>Z01</option>
<option value="Z02" selected>Z02</option>
<option value="Z03" selected>Z03</option>
</select>
</div>
<div class="col-md-2">
<br/>
<button type="submit" class="btn btn-success">Search</button>
</div>
</div>
</form>
result.blade.php
{!! csrf_field() !!}
<div class='list-group gallery'>
#if($images->count())
#foreach($images as $image)
<div class='col-sm-4 col-xs-6 col-md-3 col-lg-3'>
<a class="thumbnail fancybox" rel="ligthbox" href="/images/{{ $image->image }}">
<img class="img-responsive" alt="" src="/images/{{ $image->image }}" />
<div class='text-center'>
<small class='text-muted'></small>
</div> <!-- text-center / end -->
</a>
</div> <!-- col-6 / end -->
#endforeach
#endif
</div> <!-- list-group / end -->
ImageGalleryController.php
public function search()
{
$images = ImageGallery::get();
return view('search',compact('images'));
}
public function order(Request $request)
{
$data = $request->all();
$images = ImageGallery::where(['type',$request->$data['type']],
['wc',$request->$data['type']],
['fc',$request->$data['fc']],
['yc',$request->$data['yc']],
['sc',$request->$data['sc']])->get();
return view('result',compact('images'));
}
Web.php
// search section
Route::post('search', 'ImageGalleryController#order');
Route::get ('search', 'ImageGalleryController#search');
UPDATE
Curent my controller
public function search()
{
$images = ImageGallery::get();
return view('search',compact('images'));
}
public function order(Request $request) {
$data = $request->all();
$images = ImageGallery::where([
['type', $data['type']],
['wc',$data['type']],
['fc',$data['fc']],
['yc',$data['yc']],
['sc',$data['sc']]
])->get();
dd($images);
return view('search', compact('images'));
}
Check this code:
search.blade.php
<form action="{{ route('search') }}" class="form-image-upload" method="POST" enctype="multipart/form-data">
{!! csrf_field() !!}
<div class="col-md-5">
<strong>TYPE</strong>
<select name="type" class="form-control">
<option value="" selected>Please Select</option>
<option value="j">j</option>
<option value="w">w</option>
</select>
</div>
<div class="col-md-5">
<strong>wc</strong>
<select name="wc" class="form-control">
<option value="" selected>Please Select</option>
<option value="N0">0</option>
<option value="N1">1</option>
<option value="N2">2</option>
<option value="N3">3</option>
</select>
</div>
<div class="col-md-5">
<strong>FC</strong>
<select name="fc" class="form-control">
<option value="" selected>Please Select</option>
<option value="f01">f01</option>
<option value="f02">f02</option>
<option value="f03">f03</option>
</select>
</div>
<div class="col-md-5">
<strong>YC</strong>
<select name="yc" class="form-control">
<option value="" selected>Please Select</option>
<option value="yc1">yc1</option>
<option value="yc2">yc2</option>
</select>
</div>
<div class="col-md-5">
<strong>SC</strong>
<select name="sc" class="form-control">
<option value="" selected>Please Select</option>
<option value="Z01">Z01</option>
<option value="Z02">Z02</option>
<option value="Z03">Z03</option>
</select>
</div>
<div class="col-md-2">
<br/>
<button type="submit" class="btn btn-success">Search</button>
</div>
</form>
result.blade.php
<div class='list-group gallery'>
#if($images->count())
#foreach($images as $image)
<div class='col-sm-4 col-xs-6 col-md-3 col-lg-3'>
<a class="thumbnail fancybox" rel="ligthbox" href="/images/{{ $image->image }}">
<img class="img-responsive" alt="" src="/images/{{ $image->image }}" />
<div class='text-center'>
<small class='text-muted'></small>
</div> <!-- text-center / end -->
</a>
</div> <!-- col-6 / end -->
#endforeach
#endif
</div> <!-- list-group / end -->
ImageGalleryController.php
public function search()
{
$images = \App\ImageGallery::get();
return view('search', compact('images'));
}
public function order(Request $request)
{
$data = $request->all();
$images = \App\ImageGallery::when($data['type'], function ($query, $type) {
return $query->where('type', $type);
})->
when($data['fc'], function ($query, $fc) {
return $query->orWhere('fc', $fc);
})->
when($data['yc'], function ($query, $yc) {
return $query->orWhere('yc', $yc);
})->
when($data['wc'], function ($query, $wc) {
return $query->orWhere('wc', $wc);
})->
when($data['sc'], function ($query, $sc) {
return $query->orWhere('sc', $sc);
})
->get();
return view('result', compact('images'));
}
This is the database structure:
This is the full working code on my local system.
This is web.php file
Route::get ('search', 'ImageGalleryController#search');
Route::post('search', 'ImageGalleryController#order')->name('search');
Add csrf token in your form.
#csrf
Change order function as:
public function order(Request $request) {
$data = $request->all();
$images = ImageGallery::where([
['type', $data['type']],
['wc',$data['type']],
['fc',$data['fc']],
['yc',$data['yc']],
['sc',$data['sc']]
])->get();
return view('result', compact('images'));
}
Give name method to route:
Route::post('search', 'ImageGalleryController#order')->name('search');
You have to change something. Because your $data is an array. But you have declare as an object. For this reason you get this error.
$data = $request->all();
$images = ImageGallery::where(['type'=>$data['type']],
['wc'=>$data['type']],
['fc'=>$data['fc']],
['yc'=>$data['yc']],
['sc'=>$data['sc']])->get();

Laravel Request Input is not usable data

Ok maybe this is a noob laravel question but when I'm trying to store data from a form I used a $request->input in a query to get a needed field for insert but the query will not run. Note: does run if I just set something like $project_id = 6.
public function store(Request $request)
{
$project_id = $request->input('project_id');
$company = Project::where('id', $project_id)->first();
if(Auth::check()){
$task = Task::create([
'name' => $request->input('name'),
'project_id' => $project_id,
'company_id' => $company->id,
'days' => $request->input('days'),
'hours' => $request->input('hours'),
'user_id' => Auth::user()->id
]);
if($task){
return redirect()->route('tasks.index')
->with('success' , 'Task created successfully');
}
}
return back()->withInput()->with('errors', 'Error creating new task');
}
Note:
I've tried a couple different things I've found online like $project_id = $request->project_id or $project_id = $request['project_id']
Is request->input just used for inserts and can't be used as a normal varible?
Update: here is the create.blade form it's coming from
#extends('layouts.app')
#section('content')
<div class="row col-md-9 col-lg-9 col-sm-9 pull-left " >
<h1>Add a Task </h1>
<!-- Example row of columns -->
<div class="col-md-12 col-lg-12 col-sm-12" style="background: white; margin: 10px;" >
<form method="post" action="{{ route('tasks.store') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="project-name">Name<span class="required">*</span></label>
<input placeholder="Enter name"
id="project-name"
required
name="name"
spellcheck="false"
class="form-control"
/>
</div>
<div class="form-group">
<label for="task-days">Days Taken<span class="required"></span></label>
<input
id="task-days"
required
name="days"
type="number"
spellcheck="false"
class="form-control"
/>
</div>
<div class="form-group">
<label for="task-hours">Hours Taken<span class="required"></span></label>
<input
id="task-hours"
required
name="hours"
type="number"
spellcheck="false"
class="form-control"
/>
</div>
<input
class="form-control"
type="hidden"
name="project_id"
value="{{ $project_id }}"
/>
#if($projects != null)
<div class="form-group">
<label for="company-content">Select Project</label>
<select name="project_id" class="form-control">
#foreach($projects as $project)
<option value="{{$project_id}}">{{ $project->name }}</option>
#endforeach
</select>
</div>
#endif
<div class="form-group">
<input type="submit" class="btn btn-primary"
value="Submit"/>
</div>
</form>
</div>
</div>
<div class="col-sm-3 col-md-3 col-lg-3 col-sm-3 pull-right">
<div class="sidebar-module sidebar-module-inset">
<h4>Actions</h4>
<ol class="list-unstyled">
<li>All tasks</li>
</ol>
</div>
</div>
#endsection
Let's examine your <form> below:
<input class="form-control" type="hidden" name="project_id" value="{{ $project_id }}"/>
#if($projects != null)
<div class="form-group">
<label for="company-content">Select Project</label>
<select name="project_id" class="form-control">
#foreach($projects as $project)
<option value="{{ $project_id }}">{{ $project->name }}</option>
#endforeach
</select>
</div>
#endif
In this code, you have a hidden input with the name "project_id", and if $projects is not null, you also have a select with the name "project_id". Having multiple elements with the same name is invalid, and can cause issues.
Secondly, in this line:
<option value="{{ $project_id }}">{{ $project->name }}</option>
$project_id is the same value you have in the hidden input above. When you're looping over $projects, this should be $project->id:
<option value="{{ $project->id }}">{{ $project->name }}</option>
Lastly, make sure that $project_id is a valid value if you're going to send it, and consider adjusting your logic to only send the hidden input if $projects is null:
#if($projects != null)
<div class="form-group">
<label for="company-content">Select Project</label>
<select name="project_id" class="form-control">
#foreach($projects as $project)
<option value="{{ $project->id }}">{{ $project->name }}</option>
#endforeach
</select>
</div>
#else
<input class="form-control" type="hidden" name="project_id" value="{{ $project_id }}"/>
#endif
With all that adjusted, you should be able to retrieve the expected value with $request->input("project_id")

How to display selected tags in select option value in laravel?

This is my Post Create View
<div class="col-lg-12">
<form action="{{ route('admin.post.store') }}" enctype="multipart/form-data" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Post Title</label>
<input type="text" class="form-control" value="{{ old('title') }}" name="title" id="title"
placeholder="Enter Post Title">
<span class="text-danger">{{ $errors->first('title') }}</span>
</div>
<div class="form-group">
<label for="slug">Post Image</label>
<input type="file" class="form-control" name="image" id="image"
placeholder="Select Post Image">
<span class="text-danger">{{ $errors->first('image') }}</span>
</div>
<div class="form-group">
<label for="tags">Select Tags</label>
<select multiple class="form-control" name="tags[]" id="tags">
#foreach($tags as $id => $name)
<option id="{{ $id }}">{{ $name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<textarea class="body" name="body">{{ old('body') }}</textarea>
<span class="text-danger">{{ $errors->first('body') }}</span>
</div>
<div class="form-group">
<label for="category">Select Category</label>
<select class="form-control" name="category" id="category">
<option value="">Select</option>
#foreach($cats as $cat)
<option value="{{ $cat->id }}">{{ $cat->name }}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-success btn-block">Publish</button>
</form>
</div>
Tags have many to many relationship.
Here I can select many tags, but in the post edit view I cant see the selected tags that selected by me in the post create view.
I want to show selected tags in select option value and edit theme.
post update methods:
public function edit(Post $post)
{
$tags = Tag::all()->pluck('name', 'id');
$cats = Category::all();
return view('admin.post.edit', compact(['post', 'cats', 'tags']));
}
public function update(Post $post, Request $request)
{
$this->validate($request, [
'title' => 'required|min:3|max:255',
'slug' => 'nullable|string',
'image' => 'sometimes|mimes:jpeg,bmp,png,jpg,gif',
'body' => 'required',
'category' => 'nullable',
'views' => 'nullable',
'tags' => 'nullable',
]);
$post->title = $request->title;
$post->slug = $request->slug;
$post->body = $request->body;
$post->category_id = $request->category;
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/' . $filename);
Image::make($image)->resize(800, 400)->save($location);
$oldfilename = $post->image;
$post->image = $filename;
Storage::delete($oldfilename);
}
$post->save();
$post->tags()->sync($request->tags, false);
Session::flash('update', 'Post Updated Successfully');
return redirect()->route('admin.post.index');
}
post edit view:
<div class="col-lg-12">
<form action="{{ route('admin.post.update',$post->id) }}" enctype="multipart/form-data" method="post">
{{ csrf_field() }}
{{ method_field('patch') }}
<div class="form-group">
<label for="title">Post Title</label>
<input type="text" class="form-control" value="{{ $post->title }}" name="title" id="title"
placeholder="Enter Post Title">
<span class="text-danger">{{ $errors->first('title') }}</span>
</div>
<div class="form-group">
<label for="slug">Post Image</label>
<input type="file" class="form-control" name="image" id="image"
placeholder="Select Post Image">
<span class="text-danger">{{ $errors->first('image') }}</span>
</div>
<div class="form-group">
<label for="tags">Select Tags</label>
<select class="js-example-basic-single form-control" name="tags[]" id="tags" multiple="multiple">
</select>
</div>
<div class="form-group">
<textarea class="body" name="body">{{ $post->body }}</textarea>
<span class="text-danger">{{ $errors->first('body') }}</span>
</div>
<div class="form-group">
<label for="category">Select Category</label>
<select class="form-control" name="category" id="category">
<option value="">Select</option>
#foreach($cats as $cat)
<option <?php if ($cat->id == $post->category_id) {
echo 'selected';
} ?> value="{{ $cat->id }}">{{ $cat->name }}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-primary btn-block">Edit</button>
</form>
</div>
here:
<div class="form-group">
<label for="tags">Select Tags</label>
<select multiple class="form-control" name="tags[]" id="tags">
#foreach($tags as $id => $name)
<option id="{{ $id }}">{{ in_array($id,$post->category()->pluck('id')->toArray()) ? 'selected' : '' }}</option>
#endforeach
</select>
</div>
how can I pass selected post tags from database and show theme here and edit them.
I am using select2 plugin
In select2 I should pass data in jQuery:
$('.js-example-basic-single').select2().val({{ json_decode($post->tags()->getRelatedIds()) }}).trigger('change');
but it doesnt work :(
and I get this error
Method Illuminate\Database\Query\Builder::getRelatedIds does not exist. (View: C:\Users\M0RT3Z4\Desktop\MyBlog\resources\views\admin\post\edit.blade.php
Please help me, Thanks!
You have put the code in wrong place:
Try this:
<div class="form-group">
<label for="tags">Select Tags</label>
<select multiple class="form-control" name="tags[]" id="tags">
#foreach($tags as $id => $name)
<option id="{{ $id }}" {{ in_array($id,$post->category()->pluck('id')->toArray()) ? 'selected' : '' }}>{{ $name }}</option>
#endforeach
</select>
</div>

Resources