I have 5 columns in my database. Here are the names of the columns:
promo1
promo2
promo3
promo4
promo5
I would like to combine these columns to be able to make a foreach in my view.
I tried this:
$promos = Building::select('promo1', 'promo2', 'promo3', 'promo4', 'promo5')->where('id', $card->id)->get()->toArray();
and in my view :
#foreach($promos as $promo)
<span>{{ $promo['promo1'] }}</span>
#endforeach
But I have only one result for my foreach. Instead of 5. And I can only select one by one ($ promo ['promo1'], $ promo ['promo2']) so doing a foreach would not help
Is there a way to do that? thank you very much
When you're using get() method, you're getting a collection. Use the find() method to get an object instead of collection:
$promos = Building::select('promo1', 'promo2', 'promo3', 'promo4', 'promo5')->find($card->id)->toArray();
Then you'll be able to iterate over promos:
#foreach ($promos as $promo)
<span>{{ $promo }}</span>
#endforeach
First get the building object
$building = Building::select('promo1', 'promo2', 'promo3', 'promo4', 'promo5')->findOrFail($card->id);
then loop through the promos
#foreach ($building->getAttributes() as $key => $value)
<span>{{ $key }} : {{ $value }}</span>
#endforeach
note: using the $key here is optional
Related
I'm working on a join/find Laravel DB to retrieve the correct data, but it is showing the last entry of the database repeated 13 times.
I hope you can help me.
Here is the code.
In controller
$joinCot = Cotizaciones::findOrFail($id);
$joinCot = DB::table('cotizaciones')->join('prod_cotizaciones', 'prod_cotizaciones.id_cotizacion', '=', 'cotizaciones.id')
->join('users', 'users.id', '=', 'cotizaciones.id_usuario')
->join('clientes', 'clientes.id', '=', 'cotizaciones.id_cliente')
->select('cotizaciones.id', 'cotizaciones.id_usuario', 'cotizaciones.id_cliente', 'cotizaciones.equipo', 'cotizaciones.servicio_venta', 'cotizaciones.pdf', 'cotizaciones.fecha', 'cotizaciones.status', 'prod_cotizaciones.id as idPC', 'prod_cotizaciones.partida as partida', 'users.id as idU', 'clientes.id as idC', 'clientes.nombre_cliente')->get();
In blade
#foreach ($joinCot as $key => $value)
<div>{{ $joinCot->idPC }}</div>
#endforeach
If I make a return of $joinCot it shows
[{"id":40,"id_usuario":1,"id_cliente":1,"equipo":"Pipeta","servicio_venta":"Servicio","pdf":null,"fecha":"2021-05-27","status":"Pendiente","idPC":27,"partida":1,"idU":1,"idC":1,"nombre_cliente":"Instituto Nacional de Enfermedades Respiratorias Ismael Cos\u00edo Villegas"},{"id":40,"id_usuario":1,"id_cliente":1,"equipo":"Pipeta","servicio_venta":"Servicio","pdf":null,"fecha":"2021-05-27","status":"Pendiente","idPC":28,"partida":2,"idU":1,"idC":1,"nombre_cliente":"Instituto Nacional de Enfermedades Respiratorias Ismael Cos\u00edo Villegas"}]
I have 2 entries with idPC = 27 and the second one with idPC = 28.
But at the time to return the view the foreach just throws 28282828282828282828282828.
You are accessing wrong on inside loop $joinCot->idPC it should be $value->idPC.$value will return each row from array or object.
#if(isset($joinCot)&&count((array)$joinCot))
#foreach ($joinCot as $key => $value)
<div>{{$value->idPC }}</div>
#endforeach
#endif
$joinCot is your retrieved data array. foreach() return single row and key in every iteration. You have to access row->value.
That means,
#foreach ($joinCot as $key => $value)
<div>{{$value->idPC }}</div>
#endforeach
I have a table column which is separate with comma. Column name is 'Intro' and the values are:
Rumi, school,2018,lecturer
I need to show this comma separated value one by one. The output should be like this :
Rumi
I tried this code in my blade file :
#foreach ($evaluation as $client)
#foreach (explode(',', $client->Intro) as $client_intro)
{{ $client_intro[0]}}
#endforeach
#endforeach
but this shows nothing. what is the problem ?
Just simply remove the index
{{ $client_intro[0]}} ---->> should be --> {{ $client_intro}}
Try This:
#foreach ($evaluation as $client)
#foreach (explode(',', $client->Intro) as $client_intro)
{{ $client_intro }}
#endforeach
#endforeach
table(skill)
have many skills, columns type boolean(0,1),by laravel
i want to get the names of columns if skills value equal 1 and user_id equal 1,
without say the name of column becouse they 50 skills ,i tried this on sublime
<?php
$variable2=App\Skill::where('user_id',Auth::user()->id)
->where('job_id','null')
->get();
?>
#foreach($variable2 as $key1 => $value1)
#if($value1='1')
<span class="tags">{{ $key1 }}</span>
#endif
#endforeach
Well, looks like you forgot, that get returns a collection of skills. You must use two loops.
<?php
$userSkills = App\Skill::where('user_id',Auth::user()->id)
->where('job_id','null')
->get();
?>
<!-- loop through a list of user skills (get gives us a set of skills -->
#foreach($userSkills as $skill)
<!-- loop through skill properties -->
#foreach($skill->toArray() as $key => $value)
#if($value)
<span class="tags">{{ $key }}</span>
#endif
#endforeach
#endforeach
<?php $variable2=App\Skill::where('user_id',Auth::user()->id)
->where('job_id','null')
->where('user_id', 1)
->get();
$skills = $variable2->filter(function ($item) { return $item === 1; })->keys();
?>
#foreach($skills as $key)
<span class="tags">{{ $key }}</span>
#endforeach
I have json column where i save my orders data in it, code below is sample of that data:
[{"id":27,"name":"new product","price":7246,"quantity":"1","attributes":[],"conditions":[]}]
with code above if i have such loop in my edit page i'm able to get orders info:
#foreach($order->product_data as $data)
{{ $data['quantity'] }}
#endforeach
until here everything is good, but the problem when comes that my order has attributes "attributes":[], then i get this error:
Invalid argument supplied for foreach()
and my data in json column is like:
"[{\"id\":29,\"name\":\"effewf\",\"price\":24524,\"quantity\":\"1\",\"attributes\":[{\"attr\":{\"label\":\"Red\",\"price\":\"5000.00\"}},{\"attr\":{\"label\":\"22\\\"\",\"price\":\"900000.00\"}}],\"conditions\":[]}]"
as you see this order has 2 attributes. (can be more or less).
additional
this is how i get those data in order model:
protected $casts = [
'product_data' => 'array',
];
any idea why i get that error and how i can get my attributes data no matter if my order has attribute or not?
UPDATE
if i open edit page of order without attribute and dd the result will be like:
array:6 [▼
"id" => 27
"name" => "new product"
"price" => 7246
"quantity" => "1"
"attributes" => []
"conditions" => []
]
if load the same on order with attributes get the error above.
You should only allow to print data if exists and having the format we are expecting ,please add necessary conditions to your code like below which may prevent from getting the errors
Assuming the array you have in post is data you need to print.
#if($order->product_data) // check product_data value or not , also add key exists if needed
#if(is_array($order->product_data)) // check for product_data is array or not
#foreach($order->product_data as $data)
{{ $data['quantity'] // if array }}
{{ $data->quantity // if object }}
#if($data->attributes)
#foreach($data->attributes as $attribute) // loop through attributes
{{ $attribute->nameOfTheProperty // if object }}
#endforeach
#endif
#endforeach
#endif
#endif
But better to handle the data in controller if possible
update:
you need to convert your data into array, as your attribute property will be blank array if not having value otherwise it will be stdObject.
so your code should be : ($order->product_data should be an array if not then convert it to an array)
#if($order->product_data)
#if(is_array($order->product_data)) // assuming array
#foreach($order->product_data as $data)
{{ $data['quantity'] // if array }}
#if(count($data['attributes']) > 0) // **checked for blank array**
#foreach($data->attributes as $attribute) // loop through attributes
{{ $attribute['attr']['label'] }}
{{ $attribute['attr']['price'] }}
#endforeach
#endif
#endforeach
#endif
#endif
Tried with your sample data, and that executed without any error.
$json = "[{\"id\":29,\"name\":\"effewf\",\"price\":24524,\"quantity\":\"1\",\"attributes\":[{\"attr\":{\"label\":\"Red\",\"price\":\"5000.00\"}},{\"attr\":{\"label\":\"22\\\"\",\"price\":\"900000.00\"}}],\"conditions\":[]}]";
$jsonAsArray = json_decode($json, true);
foreach ($jsonAsArray as $data) {
echo $data['quantity'] . "\n";
if (! empty($data['attributes']) ) {
if (is_array($data['attributes'])) {
foreach ($data['attributes'] as $attribute) {
echo $attribute['attr']['label'] . ' ' . $attribute['attr']['price'] . "\n";
}
}
}
}
Outputs:
1
Red 5000.00
22" 900000.00
In your case, the product_data is not cast as an array.
You could try Defining An Accessor in your Order model, and remove the cast property of product_data
public function getProductDataAttribute($value)
{
return json_decode($value, TRUE);
}
Or Manually decode the json in your loop
#foreach (json_decode($order->product_data, TRUE) as $data)
{{ $data['quantity'] }}
#if (! empty($data['attributes']))
#foreach ($data['attributes'] as $attribute)
{{ $attribute['attr']['label'] }} {{ $attribute['attr']['price'] }}
#endforeach
#endif
#endforeach
This is how I did mine (category is a json column in the DB):
<div class="category">
<ul class="list-group">
#foreach ( json_decode( $code->category ) as $category)
<li class="list-group-item d-flex justify-content-between align-items-center">
<span class="badge badge-secondary badge-pill">{{$category}}</span>
</li>
#endforeach
</ul>
</div>
You just have to json_decode your json column to get an array and iterate over it. that's it, cheers.
I am displaying elements of an array #foreach($tags as $tag)$tag->#endforeach. The output is tag1tag2tag3. What is the possible way to sho elements of array in tag1,tag2,tag3. And how to not show, if there is only one element in array.
The selected answer is too complicated. Laravel has a simpler solution:
{{ $items->pluck('tag')->implode(', ') }}
implode() is good for echoing simple data. In real project you usually want to add some HTML or logic into the loop, use $loop variable which is available since 5.3:
#foreach ($arrayOrCollection as $value)
{{ $loop->first ? '' : ', ' }}
<span class="nice">{{ $value->first_name }}</span>
#endforeach
Use this. We can implement it using $loop->last
#foreach ($arrayOrCollection as $value)
<span class="nice">
{{ $value->first_name }}
#if( !$loop->last)
,
#endif
</span>
#endforeach
Use implode:
{{ implode(', ', $tags) }}
implode is one option or you can using join as well like this
{{ join(', ', $tags) }}
Try the first one or this one..
good luck
I believe what you are looking for might be something like this:
//have your array in php tags
//$arr = ['one', 'two', 'three']; ? >
//go through the array with foreach and if the count of the array is not equal to the las element then put coma after it
#foreach ($arr as $key => $value)
#if( count( $arr ) != $key + 1 )
{{ $value }},
#else
{{ $value }}
#endif
#endforeach
Try implode():
$arr = ['one', 'two', 'three'];
echo implode(',', $arr);
// output
one,two,three