Merge 2 Laravel query results in one object - php

I found a lot of similar questions but without a real solution for me.
I have a project on Laravel 5.4
Now, in my Controller I am preparing filters for my search.
So, Imagine that I want to filter my search by "location", and "about" fields of my Cv model.
So, I am finding distinct values of each one doing this
$arrOfTags = explode(',', $request['position']);
//separate basic search request(using some js modules that return a request with "," separator.
//Basically, find a Cv where location of "positions" is distinct
$filter0 = Cv::select('location')
->whereIn('position', $arrOfTags)
->groupBy('location')
->get();
$filter1 = Cv::select('about')
->whereIn('position', $arrOfTags)
->groupBy('about')
->get();
Now, I want to concatinate this 2 results in object named $filters
And then, in my Blade to use it like :
#foreach($filters as $filter)
<li> <input type="checkbox" name="location" value="{{$filter->location}}"/> <span> {{$filter->location}} </span> </li>
#endforeach
#foreach($filters as $filter)
<li> <input type="checkbox" name="location" value="{{$filter->about}}"/> <span> {{$filter->about}} </span> </li>
#endforeach
I tried array_merge of objects, creating a new empty object and set parameters of this objects and other stuff, but without success.

In this case you can use unique() collection method. Get the data:
$filters = Cv::select('location', 'about')
->whereIn('position', $arrOfTags)
->get();
Get unique values for each column and use results:
#foreach($filters->unique('location') as $filter)
<li> <input type="checkbox" name="location" value="{{ $filter->location }}"/> <span> {{$filter->location}} </span> </li>
#endforeach
#foreach($filters->unique('about') as $filter)
<li> <input type="checkbox" name="about" value="{{ $filter->about }}"/> <span> {{ $filter->about }} </span> </li>
#endforeach

Why are you just making it complected ?
$locationFilters= Cv::select('location')
->whereIn('position', $arrOfTags)
->groupBy('location')
->get();
$aboutFilters= Cv::select('about')
->whereIn('position', $arrOfTags)
->groupBy('about')
->get();
return view('view name',compact('locationFilters','aboutFilters'));
Then in your view:
#foreach($locationFilters as $filter)
<input value="{{$filter->location}}"/>
#endforeach
#foreach($aboutFilters as $filter)
<input value="{{$filter->about}}"/>
#endforeach

on the server side, you can do it as
$filters[] = $filter0->location;
$filters[] = $filter1->about;
on view, just print the value of the array instead of accessing the object.

You could simply use merge method to merge two collections. The merge method merges the given array or collection with the original collection. Try this-
$filters = $filter0->merge($filter1);
For further details you can see the official laravel documentation

Related

how to Concatenate an id in a foreach loop using jquery laravel

i have a foreach loop whereby i want to concatenate the id of each loop to its id jquery.i have tried this but i get the the id for the first loop only.this is my code in the blade file.
#foreach ($rentalcategories as $category)
<div class="checkbox checkbox-success">
<input type="text" value="{{ $category->id }}" class="catid">
<input type="radio" name="rentalcategory" class="rentalcattitle" id="rentalcat{{ $category->id }}" value="{{ $category->id }}">
<label for="rentalcat" class="control-label"> {{ $category->rentalcat_title }}</label><span>({{ $category->rentalhses->count() }})</span>
</div>
#endforeach
this is my jquery code
var categoryid=$(".catid").val();
console.log(categoryid);
var hsecategory= $('#rentalcat' + categoryid).prop('checked') ? $('#rentalcat' + categoryid).value : ''
on the console logging the categoryid variable am only getting the first value only for the first loop but the other one it doesn't show.how can i get the id for each loop then concatenate to an id in each loop.
here in my code i want to get the value for each loop using the id instead of class.how can i achieve this
I think because the Id as incrementing within the loop you just need to find element by id that starts with rentalcat
so something like this
$('input[id^="rentalcat"]')
credit to : Find html element which id starts with
that should give all the instances so you will need to preform an each function to get out each instance value
$('input[id^="rentalcat"]').each(function( i ) {
console.log($(this).val())
});
you can then concatenate that values or do whatever you need with the id's in the each loop
I hope this helps

Setting multiple Tag checkboxes as "Selected" from Array

Struggling with something simple!
I'm new to Laravel 8 and have a number of checkboxes which are dynamically created saving their values to an array. My problem occurs when i want to flag previously active options as "selected".
The problem appears to be with the in_array argument and where i'm creating the array..
#php
$currentTags = $prop->tags->pluck('id');
#endphp
#foreach($tags as $tag)
<div class="custom-control custom-switch">
<input type="checkbox"
#if(in_array($tag->id, $currentTags)) selected #endif
class="custom-control-input"
onclick="$(this).val(this.checked ? {{ $tag->id }} : 0)"
id="tags[{{ $tag->id }}]"
name="tags[{{ $tag->id }}]">
<label class="custom-control-label" for="tags[{{ $tag->id }}]">{{ $tag->name }}</label>
</div>
#endforeach
Error
TypeError
in_array(): Argument #2 ($haystack) must be of type array, Illuminate\Support\Collection
As #El_Vanja commented:
The error is rather clear - it expects an array, but you gave it an object of type Illuminate\Support\Collection. If you check out the documentation of that class, you'll see it has a method called all that retreives collection items as an array.
Also should change selected to checked.
change this
#if(in_array($tag->id, $currentTags)) selected #endif
To
#if(in_array($tag->id, $currentTags->toArray())) checked #endif
or
#if(in_array($tag->id, $currentTags->all())) checked #endif

Sending checked checkbox values

I'm doing a filter-by specifications on an app, and was wondering how can I implement without reloading the whole page (which I'm trying to convert to AJAX rather than PHP/Laravel alone). However my filters are based off on foreach loops
#foreach($cores as $core)
<li style="list-style: none;">
<input type="checkbox" name="core[]" id="cores" class="form-check-control" value="{{ $core->value }}"> {{ $core->value }}
</li>
#endforeach
Am trying $('#cores').val() but it is not working. I'm thinking of call it by class name then looping it to check if it is checked but it may affect performance.
The for loop is creating multiple elements with the same id, so accessing it this way won't work. Remove the id element from the checkbox, and refer to this answer for getting the value of the checked boxes in JS
try to do it this way and u can take the values
#foreach($cores as $core)
<li style="list-style: none;">
<input type="checkbox" name="core[{{ $core->value }} || paste something unique for the checkbox]" id="cores" class="form-check-control" value="1"> {{ $core->value }}
</li>
#endforeach
after that u can foreach $core and take only values that are seted and filter by them

Retrieving and passing data to form input

I have two DB tables as item and price.
In view file, foreach of items I have form element as
<input type="text" name="dc_{{$item->id}}" value="{{$price->dc_*}}">
I want * in value as dc_{{$item->id}} for an example like dc_4 or dc_7
I am unable to use {{ $price-> dc_{{$item->id}} }} for value as it is wrong syntax.
What's an alternative way to implement such logic?
You can do
<input type="text" name="dc_{{ $item->id }}" value="{{ $price->{ 'dc_' . $item->id } }}">

Looping through input array in Laravel 5

I have a basic UI where users can add a simple list with a label and a value. I want to loop through that list to store the data in a "Detail" model.
I have the following code.
Controller:
$details = $request->input('detail_label');
foreach($details as $key => $value)
{
if(!empty($request->input('detail_value.'.$key))) {
// if the detail has an existing ID
if($request->input('detail_id.'.$key)) {
$detail = Detail::find($request->input('detail_id.'.$key));
} else {
$detail = new Detail;
}
$detail->type = $request->input('detail_type.'.$key);
$detail->label = $request->input('detail_label.'.$key);
$detail->value = $request->input('detail_value.'.$key);
if($request->input('detail_privacy.'.$key) == 1) {
$detail->privacy = 1;
} else {
$detail->privacy = 0;
}
$user->details()->save($detail);
}
}
View:
#foreach($user->details as $detail)
<div class="detail">
<input type="hidden" name="detail_id[]" value="{{ $detail->id }}">
<label>Type
<select name="detail_type[]">
<option #if($detail->type == '1')selected #endif value="1">Phone</option>
<option #if($detail->type == '2')selected #endif value="2">Phone (mobile)</option>
<option #if($detail->type == '3')selected #endif value="3">URL</option>
<option #if($detail->type == '4')selected #endif value="4">Email</option>
</select>
</label>
<label>Label
<input type="text" name="detail_label[]" value="{{ $detail->label }}">
</label>
<label>Value
<input type="text" name="detail_value[]" value="{{ $detail->value }}">
</label>
<label>Private?
<input type="checkbox" name="detail_privacy[]" #if($detail->privacy == true) checked #endif value="1">
</label>
<label>Delete?
<input type="checkbox" name="detail_delete[]" value="{{ $detail->id }}">
</label>
</div><!-- / detail -->
#endforeach
Every aspect of my code works as I had planned except the detail_privacy field. It sets and unsets the boolean privacy attribute but it pays no attention to which $key I want. It always sets it according to the order in the loop. If I just set one detail to be private it will be first. If I set two, (whichever two), it will be the first and second.
Something is clearly wrong with my logic but I can't tell what.
Any help would be really appreciated. Thanks!
The reason it doesn't work is that non-checked checkboxes are not included in the post data. You may see it by dumping value of $request->input('detail_privacy').
To be able both to edit existing and add new details, you need to set keys on inputs in the form. Anything really, as long as you keep track of it. To make things easier you can add hidden input named same as the checkbox, so detail_privacy will be always present in the post data. For example:
#foreach ($user->details as $key => $detail)
<input type="hidden" name="detail_id[{{ $key }}]" value="{{ $detail->id }}">
...
<input type="hidden" name="detail_privacy[{{ $key }}]" value="0">
<input type="checkbox" name="detail_privacy[{{ $key }}]" #if($detail->privacy == true) checked #endif value="1">
...
#endforeach
If you add new fields dynamically ie. with javascript you need to respect those keys. Its quite simple though, just pass last value of $key to your js and you're set.
Also I would recommend different notation for input names: details[{{ $key }}][id] instead of detail_id[{{ $key }}]. This way controller action will become much simpler:
foreach ($details as $detail) {
if (! empty($detail['id'])) {
...
}
}
If the Boolean values are stored as TINYINTS in the Database (as in: 0 or 1); then perhaps taking out the Boolean true || false may resolve the Issue. Not Certain but guessing it's worth the try:
<!-- JUST TRY IT LIKE SO: #if($detail->privacy) checked #endif -->
<label>Private?
<input type="checkbox"
name="detail_privacy[]"
#if($detail->privacy) checked #endif value="1"
>
</label>
Or Hypothetically:
<!-- YOU MAY ALSO USE "1" LIKE SO: #if($detail->privacy==1) checked #endif -->
<label>Private?
<input type="checkbox"
name="detail_privacy[]"
#if($detail->privacy==1) checked #endif value="1"
>
</label>

Categories