Hi I have the following query:
$inc_quotes = DB::table('inc_quotes')->where('session_id', '=', $session_id)->get();
And it returns an array of arrays I believe like below:
array:36 [▼
0 => {#232 ▼
+"id": "5"
+"session_id": "1ee0556134d377c05673fce16f719b3e1077c797"
+"brand": "Acer"
+"drive": "Full Size Laptop"
+"screen": "Less than 2 Years old"
+"processor": "AMD A6"
+"condition": "No"
+"faults": "Light Damage,Heavy Damage"
+"price": "16.37"
+"name": "Alex"
+"lastname": "C"
+"email": "test#hotmail.com"
+"mobile": "12344567"
+"created_at": "2016-02-20 09:05:51"
+"updated_at": "2016-02-20 09:05:51"
}
1 => {#233 ▶}
2 => {#234 ▶}
Now I would like to extract from each array(row) for example the name and do a for each on the view to show the names for each row.
How can I extract the values?
I tried this
foreach($inc_quotes as $quote){
$quote_name = $quote->name;
}
But only returns the last value.
Any help much appreciated.
$quote_name = [];
foreach($inc_quotes as $key => $quote){
$quote_name[$key] = $quote->name;
}
EDITED
pass this to view like this.
return view('whateverYourView',compact('quote_name'));
and in view you access it with
#foreach($quote_name as $name)
{{ $name }}
#endforeach
Your $quote_name must be an array or an collection to receive all data that is comming from the array that you are iterating.
The $quote_name will be subscribed in every loop, that's why the method it will show only the last result.
Related
I was updating may images array which is found in following format:
[
"d756d3d2b9dac72449a6a6926534558a.jpg",
"b607aa5b2fd58dd860bfb55619389982.jpg",
"f937c8fddbe66ab03c563f16d5cfa50c.jpg"
]
So to delete a single image d756d3d2b9dac72449a6a6926534558a.jpg from this array column I used the filter method like below:
$collection = collect($imageColumn)->filter(
function ($valueTobeDeleted) use ($array) {
return !in_array($valueTobeDeleted, $array);
}
);
so after filter I wan to update my database with the new collection, but the new collection is in a map format like below
array:2 [
1 => "b607aa5b2fd58dd860bfb55619389982.jpg"
2 => "f937c8fddbe66ab03c563f16d5cfa50c.jpg"
]
the problem is i don't need those keys 1, and 2 my expectation was
array:2 [
"b607aa5b2fd58dd860bfb55619389982.jpg"
"f937c8fddbe66ab03c563f16d5cfa50c.jpg"
]
How can I achieve my expectation? How can I convert them to array?
Because you are using a Collection, you can do ->values() at the end so you convert all keys into integer keys and beginning from 0, like a normal non-associative array:
$collection = collect($imageColumn)->filter(
function ($valueTobeDeleted) use ($array) {
return !in_array($valueTobeDeleted, $array);
}
)
->values();
In order to re-index an array, you can use the array_values PHP function:
$arr = array_values($arr);
This will fix the keys.
Use array_values to get a an array of that associatve array.
$collection = collect($imageColumn)->
$filtered = filter(function ($valueTobeDeleted) use ($array) {
return !in_array($valueTobeDeleted, $array);
});
$filtered = array_values($filtered);
My object "fields":
array:4 [▼
0 => Fields {#10900 ▶}
1 => Fields {#11222 ▶}
2 => Fields {#11230 ▼
-id: 8
-name: "Tier"
-uuid: "5f60107fe4"
-productgroup: PersistentCollection {#11231 ▶}
-options: PersistentCollection {#11233 ▶}
-template: PersistentCollection {#11235 ▼
-snapshot: []
-owner: Fields {#11230}
-association: array:20 [ …20]
-em: EntityManager {#4288 …11}
-backRefFieldName: "fields"
-typeClass: ClassMetadata {#7714 …}
-isDirty: false
#collection: ArrayCollection {#11236 ▼
-elements: []
}
#initialized: true
}
-type: Type {#11237 ▶}
-formatstring: ""
}
3 => Fields {#11511 ▶}
]
I want to find out if a certain "templateId" exists in "fields":
foreach ($fields as $field) {
$templateId = $field->getTemplate();
$result = property_exists($templateId, 3);
}
The result is "false", even if I expect it to be true.
Entity field list: https://pastebin.com/zcuFi1dE
Template: https://pastebin.com/mVkKFwJr
First of all,
$templateId = $field->getTemplate();
return an ArrayCollection of Template (By the way you should rename your property Templates)
I believe what you want to do is check if a Template is in the array template of Fields.
So there are two proper ways to do it :
Using the contains method from Doctrine\Common\Collections\ArrayCollection
Compare an object to another
//First get the proper Template object instead of the id
$template = $entityManager->getRepository(Template::class)->find($templateId);
$templateArray = $field->getTemplate();
//return the boolean you want
$templateArray->contains($template);
Compare indexes/keys :
$templateArray = $field->getTemplate();
//return the boolean you want
$templateArray->containsKey($templateId);
But in the case you want to do the same thing but with another property than the id you can loop through your array :
Compare other attribute
//In our case, name for example
$hasCustomAttribute=false;
foreach($field->getTemplate() as $template){
if($template->getName() == $nameToTest){
$hasCustomAttribute=true;
}
}
I am going to build advance search function in laravel 5. I queried from 'itemregistrations' table by filtering a few fields such as negeriID, categoryID and operasiID. I need to do array map to calculate age value of each item and put in the array. By getting values using itemregistration table and calculating age runs okay but it problem in searching through the if statement. It cannot searching and retrieve the values through the array in the collection.
$newitem = DB::table('itemregistrations')
->select('itemregistrations.*')
->get();
//added code to get 'age' value:
$newitem->map(function ($detail) {
$detail->age = \Carbon\Carbon::createFromFormat('Y',$detail->lahir_yy)->diffInYears();
return $detail;
});
if ($request->has('negeri_lahir')) {
$newitem->where('NegeriID', '==', $request->negeri_lahir);
}
if ($request->has('kategori')) {
$newitem->where('CategoryID', $request->kategori);
}
if ($request->has('pangkat')) {
$newitem->where('OperasiID', $request->pangkat);
}
dd($newitem->get());
The problem because of the array map added, turning the collection in array values causing this error.
It is producing error:
Type error: Too few arguments to function Illuminate\Support\Collection::get(), 0 passed in C:\xampp\htdocs\
This is the array list in the collection for dd($newitem);
#items: array:1123 [▼
0 => {#709 ▶}
1 => {#680 ▶}
2 => {#681 ▶}
3 => {#712 ▶}
Collection {#671 ▼
#items: array:1123 [▼
0 => {#709 ▼
+"ItemRegistrationID": 1
+"COID": 109064
+"FType": ""
+"STNo": "0"
+"RegistrationDate": "2005-12-01"
and more attributes...
How to enable the searching through the array list?
First of all, you don't need to use select() in query.
Looks like better to make filtering in db query using when().
Try:
$newitem = DB::table('itemregistrations')
->when(request('age'), function($query){
$query->whereRaw('YEAR(curdate()) - lahir_yy >= ?', [request('age')]);
})
->when(request('negeri_lahir'), function($query){
$query->where('NegeriID', request('negeri_lahir'));
})
->when(request('kategori'), function($query){
$query->where('CategoryID', request('kategori'));
})
->when(request('pangkat'), function($query){
$query->where('OperasiID', request('pangkat'));
})
->get();
I have to following array from inputs
array:9 [
"columns" => "4"
"device_id" => array:4 [
0 => "1"
1 => "2"
2 => "3"
3 => "4"
]
"hub_id" => "11"
"usage" => array:4 [
0 => "1"
1 => "2"
2 => "3"
3 => "4"
]
....
In my foreach loop i get back only one value not all
$devices = $request->all();
foreach ($devices["device_id"] as $device) {
dd($device);
}
This will return only 1 one value not all.
I have problem displaying all the value and saving them to database.
Witch would be the fast and the right way ?
The array and the behaviour you are getting is normal.
$devices = $request->all();
foreach ($devices["device_id"] as $device) {
dd($device);
}
This will indeed return 1, because your cursor is at the first value of $devices["device_id"]. If you wait for the next iteration, it'll be 2, then 3 and 4.
Remember you can also write your foreach this way:
foreach ($devices["device_id"] as $index => $device)
, where $index will be equal to the index related to the current value.
If you want all values, you can just simply dd($devices["device_id"]), it'll return you this array:
array:4 [
0 => "1"
1 => "2"
2 => "3"
3 => "4"
]
You do not save array in a database. Databases are not supposed to save multidimensional structures, since they do not support them.
You must convert your array into a format that the database is able to save, for example JSON or PHP serialize. It is actually very common to save data in this way if you do not need to search it easily at a later time.
Nevertheless, I would use a setter in your model to achieve this:
public function setAttributeNameAttribute($values)
{
$this->attributes['attribute_name'] = json_encode($values);
}
public function getAttributeNameAttribute($values)
{
return json_decode($values);
}
I have a conditional query that works in my index controller that should return eloquent relationships but does not always return an accessible array index:
$customers = Customer::with('orders', 'regions')->orderBy('created_at', 'desc')->whereHas('regions', function($query)
{
$user_id = Auth::user()->id;
$current_user = User::with('roles')->where('id', '=', $user_id)->latest()->first();
$role_name = $current_user->roles[0]->name;
if($role_name == 'admin_master'){$query->whereIn('region', array(11, 7));}
}
)->get();
The problem is the related array is not always accessible eg order[1] and displays oddly when I dd($customers);
#relations: array:5 [▼
"orders" => Collection {#442 ▼
#items: array:2 [▼
0 => Order {#446 ▶}
1 => Order {#447 …25}
]
}
For future users, the get method gets the results as a collection. You can chain the toArray() method on it to convert it into an array.
So it will be something like $query->get()->toArray()