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

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

Related

Show collection of data using while loop

How can I show collection of data using while loop in blade file? Suppose I have some data like this
$products = Product::latest()->where('status', 1)->get();
return view('products', compact('products'));
Now in this case how can I write this $products variable in my products.blade.php file.? I don't wana use #foreach loop. Can anybody help me.?
You can use Laravel Collection's get method to retrieve a 'row' at a given key.
#php $i=0; #endphp
#while($i < $products->count())
{{ $products->get($i)->name }}
#php $i++; #endphp
#endwhile

Only return one row in foreach

I'm starting with Laravel and I'm having trouble getting the results of a query on the laravel blade.
From a list obtained through a query to MySQL 'mysql', I want to check the name it has in another table of another 'tienda' database.
Everything is fine, but it only returns the last value of the second query, it does not return all the values ​​of the $ products query with its corresponding name obtained in $ products_name.
Controller
$productos = [
'id' => $id
];
$products = DB::connection('mysql')
->SELECT("SELECT * FROM promociones_product WHERE id_promo = $id", $productos);
foreach ($products as $product)
{
$products_name = collect(DB::connection('tienda')
->table('ps_product_lang')
->where('id_product', $product->id_product)
->get(['name', 'id_product']));
}
return view('promociones-products')->with('promo', $products_name);
Blade
#foreach($promo as $product)
<tr>
<td>{{ $product->id_product }}</td>
<td>{{ $product->name }}</td>
</tr>
#endforeach
I need to make a query against the 'mysql' database and, with those results, consult its name in another database, and all the values ​​are printed on the screen.
So there are a couple of issues with the code you provided.
To start with, in your loop you are creating a new collection called 'products_name' on each loop which keeps overwriting itself.
There are lots of ways of approaching this however how I would do it is below:
$promo = []; // Initialise a new array called promo
foreach ($products as $product)
{
// Append the collection to the new array
$promo[] = collect(DB::connection('tienda')
->table('ps_product_lang')
->where('id_product', $product->id_product)
->get(['name', 'id_product']));
}
Now you have an array with all of the products in collections.
Now the loop to get that data should work.
You can then return the data to the view using a couple of methods, my preferred method is indeed compact() seen below:
return view('promociones-products', compact('promo'));
What compact() will do is grab any variable names mentioned in the view and pass it through to the view. This compact will pass the $promo variable to the view.

Object getting converted to array?

I'm trying to update a notification's data (for displaying it in a view):
$notifications = $user->notifications()->paginate(15);
foreach ($notifications as $notification)
{
$post = Post::where('id', $notification->data['post_id'])
->first();
$notification->data = $post;
}
But when I do this in my view:
#foreach ($notifications as $notification)
{{ gettype($notification->data) }}
#endforeach
It shows that the data is an array. Why does it convert the Post model object to an array and how can I stop this from happening?
Your $notification object is an instance of Illuminate\Notifications\DatabaseNotification. This is an Eloquent Model that has the following $casts property defined:
protected $casts = [
'data' => 'array',
'read_at' => 'datetime',
];
Because of this, when you access $notification->data, it will automatically be cast to an array.
To resolve your issue, and to reduce the number of database queries, you should just build a separate lookup collection of posts, and pass that into the view.
First, build an array of all the Post ids. Then, run one query to get all the Post|s for those ids. After that, re-key the resulting Collection of Post|s by the id for easy lookup later in the view. Make sure to pass your Collection of Post|s to the view.
$notifications = $user->notifications()->paginate(15);
$postIds = [];
foreach ($notifications as $notification) {
$postIds[] = $notification->data['post_id'];
}
$posts = Post::whereIn('id', array_unique($postIds))->get()->keyBy('id');
Then, in your view:
#foreach ($notifications as $notification)
{{ $posts->get($notification->data['post_id']) }}
#endforeach
You were not updating in $notifications that's why you are seeing old array not the new object you wanted to save.
foreach ($notifications as $key => $notification)
{
$post = Post::where('id', $notification->data['post_id'])->first();
$notifications[$key]->data = $post;
}

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.

Assigning a variable to each row from a Get query

In my controller, I'm selecting all rows from a table, lets call it Users.
$users = User::get();
Let's say I want to assign a variable to each row from the Users table, that determines how old they were 10 years ago
I'm assuming I have to use a foreach
foreach ($users as $user) {
$decadeAgo = $user->age - 10;
}
Now in my blade, how can I display each user row, while also displaying the $decadeAgo variable?
try this as official laravel suggestion for blade templates:
#foreach ($users as $user)
<p>{{ $user->age - 10 }}</p>
#endforeach
You can iterate over the results and address each object by reference:
foreach ($users as &$user) {
$user->decadeAgo = $user->age - 10;
}
Then, in your blade template you will have access to the element you created on the $user object.
{{ $user->decadeAgo }}

Resources