Laravel 5.2 proper foreach syntax - laravel-5

what is the difference between the following syntax ?
foreach($products as $product) {
// loop body
}
and
foreach($product as $product) {
//loop body
}
got error some time when second one is used.
Thanks

This syntax is wrong
foreach($product as $product) {
//loop body
}
As we loop through the $products and get out every single $product of it
so we pass the array first then we follow it by the name of the single variable we want to use later your foreach loop should be like this:
foreach($products as $product){
//loop body
}

Related

Laravel Collection paginate does not exist

I'm trying to implement basic pagination when retrieving notifications, but I get the following error.
Method
Illuminate\Notifications\DatabaseNotificationCollection::paginate does
not exist.
public function index()
{
$messages = collect();
$notifications = auth()->user()->unreadNotifications->paginate(5);
foreach ($notifications as $notification) {
$message = NotificationToMessageFactory::make($notification->type)
->toMessage($notification->data);
$messages->push($message);
}
}
You've to call paginate() on query builder instance not on a collection.
Correct syntax will be :
$notifications = auth()->user()->unreadNotifications()->paginate(5);
You should paginate before looping through the collection, otherwise you will be retrieving all records matching the query, when you only need 5. Like this:
$messages = collect();
$notifications = auth()->user()->unreadNotifications()->paginate(5);
foreach($notifications as $notification) {
$message = NotificationToMessageFactory::make($notification->type)->toMessage($notification->data);
$messages->push($message);
}

Loop through Laravel eloquent relationship in controller

I have two models with relationship methods,
Product
public function facts()
{
return $this->hasMany('App\Fact');
}
Facts
public function products()
{
return $this->belongsTo('App\Product');
}
I'm trying to get access to relationship column name and loop through it
$product = Product::where('slug', 'some-slug')->with('facts')->get();
this works but how to select a column called 'name' and loop through it? I have tried
foreach($products as $product){
$sum = $facts->name;
}
dd{$sum}
Exception: Property [name] does not exist on this collection instance
You are trying to pull the name field from a collection of facts, which won't have a property for that whole collection called name. You can use two loops. Example at the simplest level:
foreach ($product as $products) {
foreach($products->facts as $fact){
$sum = $facts->name;
echo $sum;
}
}
Since it's a hasMany relationship, you can pluck name from the collection
foreach ($product as $products) {
$sum = implode('', $products->facts->pluck('name')->toArray());
dd($sum);
}
Not sure where you have this variable from but you are not using the iterator in your foreach loop:
foreach($products->facts as $fact){
$sum = $facts->name;
}
What is $facts? It sounds like it is a Collection. Also what is $products, you created $product. You want to be using $fact the current iterated Fact for this Product:
$product = Product::where(....)->('facts')->first();
foreach ($product->facts as $fact) {
...
$something = $fact->name;
...
}

Can it possible to save the array as a record in table using eloquent in laravel 5.3?

I am using eloquent model and there is json request which contains array and i am prossessing it using foreach like folloeing:
public function save(Request $request){
$i = 0;
$flag = 1;
foreach ($request->all() as $record) {
if($flag){
$flag = 0;
continue;
}
else{
$user = \App\barcodedb::create($record);
}
}
}
is it the correct way to save the record from array?
Try like this
$request_data = $request->all();
$data = json_decode($request_data['data']);
Store array in $data and use it
There is no need for a foreach loop. After the JSON is converted to an array, you can just parse this array as the only argument in the insert method, like this:
App\barcodedb\insert($data);
Laravel will automatically recognize such an array as an array containing multiple new records.
See this answer: https://stackoverflow.com/a/13595393

htmlentities() expects parameter 1 to be string, array given? Laravel

I've found many question realated to my problem but couldn't found an answer yet. It's about my foreach loop in my blade.
I want to print all product-names in my blade but I couln't figure out how to do that.
thats how I'm getting the products:
--- current code:
// controller
$id_array = Input::get('id');
$products= Products::whereIn('id', $id_array)->get();
$product_name = [];
foreach($products as $arr)
{
$product_name= $arr->lists('name');
}
returning $product_name gives me this as a output:
["football","cola","idontknow","freshunicorn","dummy-data"]
In my blade is just a simple:
#foreach($products as $product)
{{ $product}}
#endforeach
Error: htmlentities() expects parameter 1 to be string, array given
Thanks for your help and time.
It seems you are getting an object in an array in an array.
Like this:
array(
array(
object
)
)
It happens because you use the get() function to retrieve you model. The get() function always "wants" to retrieve multiple models. Instead you will have to use the first() function.
Like this:
foreach($id_array as $arr)
{
$want2editarray[] = Product::where('id', $arr)->first();
}
Hope it helps :)
Edit after #Wellno comment
That's probably because Product::where('id', $arr)->first(); returns null because it did not find anything.
I forgot to add a check after the retrieving of the product.
This can be done like this:
foreach($id_array as $arr)
{
// First try to get model from database
$product = Product::where('id', $arr)->first();
// If $product insert into array
if ($product) $want2editarray[] = $product;
}
Why do you use loop with IDs? You can find all products by IDs:
$products = Product::whereIn('id', $id_array)->get();
And then use $products in the blade template
#foreach($products as $product)
{{ $product->name }}
#endforeach
try to use Model/Eloquent to fetch data.
View should only display the data and not fetching directly from DB or do heavy calculations.

laravel-dompdf how to get multiple records into the data array

I have this code to try to generate a report on all records in a table:
$items = Line::all();
$data = $items->toArray();
$pdf = PDF::loadView('pdf.catalogue', $data);
return $pdf->stream();
How do I access the array in my Blade template? I have tried
#foreach ($data as $item)
but that does not work.
How you usually pass these variables into blade is by a named array, meaning you would assign it as so.
$data['items'] = $items->toArray();
In your template you should have the variables $items containing the array.
#foreach($items as $item)
...
#endforeach

Resources