Index Controller
public function index()
{
$blogs = Blog::all();
$categories = Category:all();
return view('blog', compact('blogs', 'categories'));
}
We have something like the following code on the blog page. First we get all the available categories, then a list of all blogs.
#extends('layouts.app')
#section('content')
<div class="container">
<div class="category-filter" id="filter">
<div class="category-filter_item active">All</div>
#foreach($categories as $category)
<div class="category-filter_item">{{ $category->title }}</div>
#endforeach
</div>
#foreach($blogs as $blog)
<div class="blog-list {{ $blog->category_id}}">
<h2 class="blog_title">{{ $blog->title }}</h2>
</div>
#endforeach
</div>
#endsection
Can you please help to suggest a filtering function that, when choosing a specific category, will pull up all blogs from this category by ID?
JavaScript
document.querySelectorAll('.category-filter_item').forEach(el => {
el.addEventListener('click', () => {
document
.querySelector('.category-filter_item.active')
.classList.remove('active');
el.classList.add('active');
You could use ajax in your case by sending an ajax request to your backend and you handle the data, then you return a response, this an example of a function in controller.
public function ajaxResponse(Request $request){
if ($request->ajax()) {
$cat_id = $request->input('cat');
$blogs = Blog::query();
if ($cat_id != null) {
$blogs->whereHas("categories", function ($query) use ($cat_id) {
$query->whereIn('category_id', explode(',', $cat_id));
})->get();
}
$blogs = $blogs->get();
$blog = view('articles.ajaxblogs', ['blogs' => $blogs])->render();
}
return response()->json(['blog' => $blog]);
}
Make sure to include category id in request.
Related
controller
public function rooms_detail(Request $request)
{
$data['room_id'] = $request->id;
$data['result'] = Rooms::find($request->id);
echo $data['result'];
return view('rooms.rooms_detail', $data);
}
view:rooms/rooms_detail
#foreach($result as $row)
<div class="hero-text">{{ $row->name }}</div>
#endforeach
In this code I have a controller function where I am run a query inside the Rooms Model which works fine and my data look like {"id":16,"user_id":10088,"name":"5 \u2b50 RESORT RETREAT W\/HEATED POOL SPRAWLING GROUNDS"}. but I am unable to fetch this data in my view file. So, How can I ndo this? Please help me.
Thank You
In Docs of Laravel, you may also retrieve single records using find or first: https://laravel.com/docs/5.8/eloquent#retrieving-single-models
So
$data['result'] = Rooms::find($request->id);
return a single model not collection of models.
You should change your code in view:rooms/rooms_detail
//#foreach($result as $row) => remove foreach
<div class="hero-text">{{ $result->name }}</div>
//#endforeach
I think you don't need to loop it. since you are using find function. Just call it directly on your view
<div class="hero-text">{{ $result->name }}</div>
find function will give you the Model if it find something or it will return null
or if you want change you eloquent query.
$data['result'] = Rooms::where('id', $request->id)->get();
I would return the data like this in your controller:
return response()->view('rooms.rooms_detail', [
$result => $data['result'],
$roomID => $data['room_id']
]);
It's the recommended correct way to return responses https://laravel.com/docs/5.8/responses
And then in your blade:
<div class="hero-text">{{ $result->name }}</div>
You don't need to convert collection to array since you are using eloquents find method which will return a collection not an array
You can simply use the below code
public function rooms_detail(Request $request)
{
$room_id = $request->id;
$data = Rooms::find($request->id);
echo $data['result'];
return view('rooms.rooms_detail', $data);
}
and then in your view
<div class="hero-text">{{ $data->name }}</div>
public function rooms_detail(Request $request)
{
$room = Rooms::find($request->id);
return view('rooms.rooms_detail')->with('room',$room);
}
At View data page
<div class="hero-text">{{ $room->name }}</div>
you are fetching only one data so do not need to loop
I am pushing the 'name' instead of the 'id' value to my database. I need the correct eloquent call in order to display the specialty->id in my database rather than the name of the specialty itself. In this code, I am attempting to get the id in the $talents variable and use it as a value. However, when I attempt this, the selector does not let me choose more than one option. I THINK I NEED MULTIPLE VARIABLES FOR THIS, JUST NOT SURE HOW?
My view:
<div class="container">
{{ csrf_field() }}
<strong>Select Specialty:</strong>
<select id="multiple-checkboxes2" multiple="multiple" name="specialties" value="specialties_id">
#if($specialties)
#foreach($specialties as $specialty)
<option value= "{{ $talents }}">{{$specialty->name}}</option>
#endforeach
#endif
</div>
</select>
{!! Form::close() !!}
<script type="text/javascript">
$(document).ready(function() {
$('#multiple-checkboxes2').multiselect();
});
Client Store Controller
public function store(Request $request)
{
//
Client::create([
'specialties' => $request->specialties,
] );
return redirect('/accounts');
}
display controller
public function display($id)
{
*experimental*
$specialties=Specialty::select('id', 'name')->orderBy('id',
'asc')->get();
$talents=Specialty::select('id')->where('name', $specialties)->get();
*/experimental
return view('accounts/display', compact('accounts', 'specialties', )->withAccount($accounts);
}
}
My html is like this :
<div class="form-group has-feedback{{ $errors->has('kdkotama') ? ' has-error' : '' }}">
<select class="form-control" name="kdkotama" id="kdkotama">
<option value="">---- Pilih Kotama----</option>
#foreach($tkotam as $tkotam)
<option value="{{$tkotam->kdkotama}}">{{$tkotam->nmkotama}}</option>
#endforeach
</select>
#if ($errors->has('kdkotama'))
<span class="help-block">
<strong>{{ $errors->first('kdkotama') }}</strong>
</span>
#endif
</div>
<div class="form-group has-feedback{{ $errors->has('kdsatker') ? ' has-error' : '' }}">
<select class="form-control" name="kdsatker">
<option value="">---- Pilih Satker ----</option>
</select>
#if ($errors->has('kdsatker'))
<span class="help-block">
<strong>{{ $errors->first('kdsatker') }}</strong>
</span>
#endif
</div>
My javascript is like this :
<script>
$(document).ready(function() {
$("#kdkotama").change(function() {
console.log($("#kdkotama").val());
$.getJSON("../dropdowns/satkers/" + $("#kdkotama").val(), function(data) {
var $satkers = $("#kdkotama");
$satkers.empty();
$.each(data, function(index, value) {
$satkers.append('<option value="' + index +'">' + value + '</option>');
});
$("#kdkotama").trigger("change"); /* trigger next drop down list not in the example */
});
});
});
</script>
My routes/web is like this :
Route::get('dropdowns/satkers/{id}', 'DropDownController#getSatkers');
My controller is like this :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\TSatkr
class DropDownController extends Controller
{
public function getSatker($id)
{
$satkers = TSatkr::where('kdkotama', '=', $id)->get();
$options = array();
foreach ($satkers as $satker) {
$options += array($satker->kdsatkr => $satker->nmsatkr);
}
return Response::json($options);
}
}
I added this: console.log ($ ("# kdkotama"). val ()); in javascript. when I select kotama, the results of console.log that appear. but in the console, it did not succeed in calling controller. whereas the code, it looks like it is correct
is there anyone who can help me?
I faced so many problem to generate dynamic drop-down but now I do like this which is more powerful and useful to set dynamic drop-down value.
Lets generate DOM using method which can help us to generate dynamic DOM with one truth or source..
//Controller/HelperController.php
class HelperController
{
public static function ajaxDynamicDropDown($changeDropdown, $replaceDropdown, $url, $empty = []) {
$html = '<script type="text/javascript">';
$html.='jQuery(document).ready(function($) {';
$html.='jQuery("select[name=\'' . $change_dropdown . '\']").change(function(e){';
$html.='jQuery.ajax({';
$html.='type: "'.$action_type.'",';
$html.='url: "' . $url . '",';
$html.='dataType:"json",';
$html.='data: jQuery(this).parents("form").find("input,select").not("[type=hidden][name^=_]").serialize(),';
$html.='success:function(data){';
$html.=' jQuery("select[name=\'' . $replace_dropdown . '\']").find("option:not(:first)").remove();';
if (!empty($empty)) {
foreach ($empty as $key => $emt) {
$html.=' jQuery("select[name=\'' . $emt . '\']").find("option:not(:first)").remove();';
}
}
$html.=' jQuery.each(data, function(key,value){';
$html.=' jQuery("select[name=\'' . $replace_dropdown . '\']").append(\'<option value="\'+key+\'">\'+value+\'</option>\');';
$html.='});';
$html.='}';
$html.='});';
$html.='});';
$html.='});';
$html.='</script>';
return $html;
}
}
Benefit of it is I don't have to write change event for each dropdown. Also no need trigger.
// Blade File:
{!! Form::select('country_id',['1'=>'Test 1','2'=>'Test 2'],null,[]) !!} // First Dropdown with value
{!! Form::select('state_id',[],null,[]) !!} // Second Dropdown will set based on first one.
<script type="text/javascript">
{!! HelperController::ajaxDynamicDropDown('country_id','state_id',URL::to('ajax/states'),['state_id','city_id']) !!}
</script>
Now I am going to use implicit route controller. Using that I get controller methods based on the HTTP request type and name.
Mean in ajax if I used POST method request then in my controller my method name will be like postState() or if GET request then same getState(). For more please click here
//routes.php
Route::controller('ajax', 'AjaxController');
Here is code sample of AjaxController
// AjaxController.php
class AjaxController
{
public function postState()
{
// of course here I get Input by using request()->get('input_name')
return ['1'=>'test'];
}
}
Also you can set old value when validation going false with old() in AjaxController.
You can also use it for multiple dependencies like state if came from country now it can be possible you need to get city from state same method you can use for it..
I can get the id of selected list using javascript. Like this.
<script>
function showCategoryOptions(s)
{
console.log(s[s.selectedIndex].value);
}
</script>
But I'm thinking how can I passed the value of the selected list in my stored procedure? How can I make a variable to get the value of selected list and passed it into my stored procedure? For I'm able to get the values.
SQL:
SELECT id FROM categories WHERE category_type = p_SelectedItem;
Here when I'm gonna equal the selected item in list. But still don't have any idea how will do this. Any help would appreciated!
Controller:
public function getDocuments()
{
$resultCategory = DB::table('categories')->get();
$myResult = DB::select('call getCategoryIdStoredProc(?)',array ($category));
return view ('document.create')with('resultCategory', $resultCategory);
}
I passed an array here in $myResult but unfortunately it gives me a error.
Undefined variable: category
Migration:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoriesTable extends Migration
{
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('category_type');
});
}
public function down()
{
Schema::drop('categories');
}
}
Routes:
Route::get('/create',
[
'uses' => '\App\Http\Controllers\DocumentController#getDocuments',
'as' => 'document.create',
'middleware' => 'auth',
]);
Form:
<div class = "form-group">
<label for = "category" class = "control-label">Category:</label>
<select onChange = "showCategoryOptions(this)" name = "category" class = "form-control">
#foreach ($resultCategory as $categoryList)
<option value = "{{ $categoryList->id }}">{{ $categoryList->category_type }}</option>
#endforeach
</select>
</div>
I have an AJAX call in the View, and its having difficulties pulling from DB to the populate the drop down list. The DB has been populated. Inside the browser console I can see it has found the correct ID, but I receive the following error:
"Failed to load resource: the server responded with a status of 500 (Internal Server Error)"
Clicking this link take me to a server error:
"The parameters dictionary contains a null entry for parameter 'serviceId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.JsonResult GetServiceDetails(Int32)' in 'YardLad.Controllers.ServiceController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters"
Here is the code I have so far:
AJAX Call:
function GetServices() {
$.ajax({
type: "GET",
url: "/Service/GetServices",
data: { serviceAreaId: $('#ServiceAreaId').val() },
datatype: 'JSONP',
async: true
})
.done(function (services) {
$('#ServiceId').empty(); //commenting this line gets the field to never populate with nulls, leaving the
//"loading services..." there permanently, also brings up the request a contractor button.
$.each(services, function (i, service) { //the i is the index being passed to it... service is the value
$("#ServiceId").append(
$('<option/>')
.attr('value', this.ServiceId)
.text(this.Name)
);
});
GetServiceDescription();
});
}
Controller:
//
// GET: Service/GetServices/
public JsonResult GetServices(int serviceAreaId)
{
// selected service area
var selectedServiceArea = db.ServiceAreas.Where(sa => sa.ServiceAreaId == serviceAreaId).SingleOrDefault();
var currentDate = DateTime.Now.AddHours(2);
// list of contractors that are listed (and not expired) and have at least one contractor service added
var contractors = db.Contractors.Where(c => c.IsActive == true).Where(c => c.ExpiresOn.Value >= currentDate).Where(c => c.ContractorServices.Count >= 1).ToList();
HashSet<int> contractorIds = new HashSet<int>(contractors.Select(x => x.ContractorId));
// filter list of contractors to include only those who offer services in the selected service area
var primary = db.Contractors.ToList().FindAll(x => contractorIds.Contains(x.ContractorId))
.Where(c => c.ServiceAreaId == serviceAreaId).Distinct().ToList();
var secondary = db.ContractorServiceAreas.ToList().FindAll(x => contractorIds.Contains(x.ContractorId))
.Where(csa => csa.ServiceAreaId == serviceAreaId).Select(x => x.Contractor).Distinct().ToList();
foreach (var contractor in secondary)
{
if (primary.Contains(contractor) == false)
{
primary.Add(contractor);
}
}
// only return services in the selected service area that contractors have added
HashSet<int> filteredContractorIds = new HashSet<int>(primary.Select(x => x.ContractorId));
var services = db.ContractorServices.ToList().FindAll(x => filteredContractorIds.Contains(x.ContractorId))
.Select(x => x.Service).Distinct().OrderBy(s => s.ServiceCategory.Name).ThenBy(s => s.Name)
.Select(x => new {
ServiceId = x.ServiceId,
Name = x.Name
});
return this.Json(services, JsonRequestBehavior.AllowGet);
}
//
// GET: Service/GetServiceDetails/1
public JsonResult GetServiceDetails(int serviceId)
{
var details = db.Services.Where(s => s.ServiceId == serviceId)
.Select(x => new
{
Description = x.Description,
BasePrice = x.BasePrice
});
return this.Json(details, JsonRequestBehavior.AllowGet);
}
.cshtml
#using (Html.BeginForm("RequestService", "Service", FormMethod.Post))
{
<div class="two-third" style="margin-right: 0;">
<div id="requestService" style="overflow: auto">
<h2>Request a Service</h2>
#Html.ValidationSummary(true)
<div class="display-label">Select a State</div>
<div class="editor-field">
<select id="StateId" name="StateId">
<option value="0">loading states...</option>
</select>
</div>
<div class="display-label">Select a Service Area</div>
<div class="editor-field">
<select id="ServiceAreaId" name="ServiceAreaId">
<option value="0">loading service areas...</option>
</select>
</div>
<div class="display-label">Select a Service</div>
<div class="editor-field">
<select id="ServiceId" name="ServiceId">
<option value="0">loading services...</option>
</select>
</div>
<div class="selectedService" style="display: none;">
<div class="display-label">Service Description</div>
<div class="editor-field" id="ServiceDescription"></div>
<div class="serviceOptions" id="ServiceOptions"></div>
<div style="text-align: right;">
<input type="submit" id="SubmitRequest" value="Select a Contractor" />
</div>
</div>
</div>
</div>
<div class="one-third" style="float: right; margin-top: 0;">
<div id="summary">
<h3>Yard Lad Service Estimate</h3>
<p>This is an initial Yard Lad estimate. The end total may be higher or lower based upon the contractor you choose,
as well as the contractors on-site assessment. Payment adjustments are easy to make on site or online after the
service has been completed.</p>
<div style="font-weight: bold;">Subtotal: $<span class="subtotal">0.00</span></div>
</div>
</div>
<input type="hidden" class="stateId" name="StateId" value="0" />
<input type="hidden" class="serviceAreaId" name="ServiceAreaId" value="0" />
<input type="hidden" class="serviceId" name="ServiceId" value="0" />
After changing the Ajax call "url" The server error has slightly changed. I provided a picture of the update below:
Server Error Image
When your server receives the HTTP Get request, it is expecting an Id in the query string inside of the url(ex Service/GetServices/1), which in in request header. Your Id is actually in the request body not in url. That is why your server code is complaining. To make this work, you can change your JavaScript code to
function GetServices() {
$.ajax({
type: "GET",
url: "/Service/GetServices/?serviceId=" + $('#ServiceAreaId').val(),
dataType: "jsonp",
async: true
})
.done(function (services) {
$('#ServiceId').empty(); //commenting this line gets the field to never populate with nulls, leaving the
//"loading services..." there permanently, also brings up the request a contractor button.
$.each(services, function (i, service) { //the i is the index being passed to it... service is the value
$("#ServiceId").append(
$('<option/>')
.attr('value', this.ServiceId)
.text(this.Name)
);
});
GetServiceDescription();
});
}