Include id from drop down selector with eloquent laravel and html - javascript

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);
}
}

Related

Filtration data by category in Laravel

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.

Laravel - how to send some value of a parameter from a blade view files to a controller?

How to send value "{{$ item-> id}}" to some method in a controller?
e.g. show.blade.php - contains the value:
"{{$ item-> id}}"
MyController.php - contains the method:
public function results(Request $request){
//and here I want to use the value {{$ item-> id}}
}
Just make a form and post it , or have some hyperlink
<form method="POST" action="/route_to_your_controller">
{{ csrf_field() }}
<input type="hidden" name="item_id" value="{{$item->id}}" required>
</form>
Route
Route::post('/route_to_your_controller', 'yourController#results');
Controller
public function results(Request $request){
{
$name = $request->input('item_id')
}
In your MyController use
public function results(Request $request, Item $item){
//and here I want to use the value {{$ item-> id}}
$item_id = $item->id;
}
You also have access to all the fields of item.

How to dynamic dropdown list in laravel 5.3?

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..

How to find the closest div by ID and then find the ID's of all forms inside that div

I am looking to to find the closest div with an class of 'form_wrap' to the button when clicked and then find the ID's of all forms inside that div.
The forms sit as part of two Laravel foreach loops and have been given individual dynamic ID numbers. These ID numbers need to be collected and then submitted.
<div class="form_wrap">
#foreach ($workouts as $workout)
<?php $formid="form_".$x."_".$f;?>
{!! Form::open(array('route' => 'workoutshared.store', 'method' => 'POST', 'ID' => $formid)) !!}
{{ csrf_field() }}
{{ Form::hidden('user_id', Auth::user()->id)}}
{{ Form::hidden('date', $entry)}}
{{ Form::hidden('weight', $workout->weight)}}
{{ Form::hidden('exercise', $workout->exercise)}}
{{ Form::hidden('reps', $workout->reps)}}
{{ Form::hidden('sets', $workout->sets)}}
<button id="submit" class="btn btn-default">Share</button>
{{ Form::checkbox('share', null, array('class' => 'form-control', 'required' => ''))}}
{!! Form::close() !!}
<tr>
<th>{{$workout->exercise}}</th>
<td>{{$workout->weight}}</td>
<td>{{$workout->reps}}</td>
<td>{{$workout->sets}}</td>
</tr>
<?php $f++; endforeach;?>
</div>
There are many details you've left out, so the answers may need to be modified to match.
For example - do you want to allow the form submission? Intercept it? Or do you care?
Another point is - what do you want to do with the ID's once you have them?
This code will do what you've asked. It uses event delegation, so you should be able to load it in your <head>, and it will still work as requested.
// Bind to the click event of all form buttons
$(document).on('click', 'form button', function() {
// Find the closest div
var wrap = $(this).closest('div.form_wrap');
// Then, find all form ID's inside of the div:
wrap.find('form').each(function() {
var id = $(this).prop('id');
});
});
What you do with those ID's is up to you, but there's several options, depending on your needs.
I think you want $( "[id^='form_']" ) which finds any ID that starts with "form_" although using a class is a better option when trying to find more than one element on a page.
var formWrap = $( "#SomeSpecificID" ).parent();
var formsInsideThatID = formWrap.children().attr('id');

How to passed selected list in stored procedure using Laravel 5.2

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>

Categories

Resources