Accessing in arrays using Twig templating engine - php

I am able to grab {{ value.title }} which displays fine however getting the inner array value it is not showing and not sure what I'm doing wrong here. I have not used Twig before.
PHP
$product_array = array();
foreach ($shopifyProducts as $product) {
$item = array(
"title" => $product["title"], // product title
"variants" => array() // for now an empty array, we will fill it in the next step
);
foreach($product["variants"] as $variant) {
$item["variants"][] = array(
"barcode" => $variant["barcode"], // product barcode
"sku" => $variant["sku"] // product SKU
);
}
$product_array[] = $item; // now we add the item with all the variants to the array with all the products
}
TWIG
<div class="table-responsive">
<table class="table">
<thead>
<th>Title</th>
<th>Barcode</th>
<th>SKU</th>
</thead>
<tbody>
<tr ng-repeat="value in remote_data">
<td>{{ value.title }}</td>
<td>{{ value.variants.barcode }}</td>
<td>{{ value.variants.sku }}</td>
<td>{{ value.variants }}</td>
</tr>
</tbody>
</table>
</div>
If I output value.variants it outputs
[{"barcode":"5060315468600","sku":"PLU#1"}]
But I can't seem to get the barcode and sku to display.

The variants attribute is an array, you should cycle in it, as example:
{% for variant in value.variants %}
<td>{{ value.title }}</td>
<td>{{ variant.barcode }}</td>
<td>{{ variant.sku }}</td>
{% endfor %}
Here a working example with the sample data provided.
Probably, seen your code, is better you change the structure of your data (you need to display always the product's title) and simplify the twig code, as example I propose you the following:
PHP
$product_array = array();
foreach ($shopifyProducts as $product) {
foreach($product["variants"] as $variant) {
$product_array[] = array(
'title' => $product["title"], // always display the product title
"barcode" => $variant["barcode"], // product barcode
"sku" => $variant["sku"] // product SKU
);
}// end foreach
}// end foreach
TWIG
<div class="table-responsive">
<table class="table">
<thead>
<th>Title</th>
<th>Barcode</th>
<th>SKU</th>
</thead>
<tbody>
<tr ng-repeat="value in remote_data">
<td>{{ value.title }}</td>
<td>{{ value.barcode }}</td>
<td>{{ value.sku }}</td>
</tr>
</tbody>
</table>
</div>

Related

Laravel view foreach with two properties

i need help with my foreach loop in view
Controller.php
$expenses = Expense::groupBy('category_id')->selectRaw('sum(amount) as sum, category_id')->pluck('sum','category_id');
$categories = Category::all();
return view('dashboard.index', compact('expenses','categories'));
index.php
<table class="table">
<thead>
<th>Category</th>
<th>Expenses</th>
</thead>
<tbody>
#foreach($categories as $category)
<tr>
<td>{{ $category->name }}</td>
#foreach($expenses as $expense)
<td>{{ $expense }}</td>
#endforeach
</tr>
#endforeach
</tbody>
</table>
I get the output like this.
enter image description here
It outputs the expense 2 times, is there a limiter for "foreach loop" or is there another way on doing this?
You need to add a condition for that $category->id is the same as category_id
#foreach($expenses as $key => $expense)
#if($key == $category->id)
<td>{{ $expense }}</td>
#endif
#endforeach
The right way to do it is by using join or relationship.
$expenses = Expense::join('categories','categories.category_id','expenses.category_id')->groupBy('expenses.category_id')->selectRaw('sum(expenses.amount) as sum, expenses.category_id','categories.name')->get();
<table class="table">
<thead>
<th>Category</th>
<th>Expenses</th>
</thead>
<tbody>
#foreach($expenses as $expense)
<th>{{ $expense->name }}</th>
<td>{{ $expense->sum }}</td>
#endforeach
</tbody>
</table>
You should limit the results in controller, but here's how you can accomplish this in a blade. Not pretty
#foreach ($element['subs'] as $item)
#if($loop->index < 10)
// Your code
#endif
#endforeach
You should compare category_id with category->id.
#foreach($categories as $category)
<tr>
<td>{{ $category->name }}</td>
#foreach($expenses as $expense)
#if($expense->category_id == $category->id )
<td>{{ $expense->sum }}</td>
#endif
#endforeach
</tr>
#endforeach

Database sql server with results but view is empty

something really strange is happening. So I have a table named Lactinfo_News with 1 row. I've created also a view called LACTINFO_VW_LatestNews which have "SELECT * FROM Lactinfo_News" and is returning the same 1 row.
I'm using Eloquent and In my news Manager I have,
public function GetLatestNews($rowsPerPage) {
$list = DB::table('LACTINFO_VW_LatestNews')
->orderBy('RegistedDate', 'DESC')
->paginate($rowsPerPage);
return $list;
}
where $rowsPerPage = 30.
In my controller I have,
// >> current page
$page = '1';
if (! empty ( $request->query ( 'page' ) )) {
$page = $request->query ( 'page' );
}
// >> search
$nM = new NewsManager();
$list = $nM->GetLatestNews($page, $this->nbOfRowsPage);
return view ('admin.news.index', [
'results' => compact($list),
'page' => $page,
'startDate' => $startDate,
'endDate'=>$endDate
] );
}
And in my view,
<table id="news-results" class="hover responsive" style="margin-top: 20px;">
<thead>
<tr>
<th scope="column">Título</th>
<th scope="column">Descrição</th>
<th scope="column">Data Início</th>
<th scope="column">Ficheiro</th>
<th scope="column">Registada em</th>
<th scope="column">Criada por</th>
</tr>
</thead>
<tbody>
#if (count($results) > 0)
#foreach ($results as $r)
<tr>
<td>{{ $r->title }}</td>
<td>{{ $r->description }}</td>
<td>{{ Carbon\Carbon::parse($r->startDate)->format('d/m/Y') }}</td>
<td>{{ $r->fileURL }}</td>
<td>{{ $r->registedDate }}</td>
<td>{{ $r->createdBy }}</td>
</tr>
#endforeach
#else
<tr><td colspan="11">Não existem notícias criadas</td></tr>
#endif
</tbody>
</table>
If I dump the $results var is empty..
What's happening? This is really strange :S I don't think I need to execute any artisan command because I've add a new function to my manager but I'm stuck with this problem for a few days...
You are using compact on an object of type LengthAwarePaginator, which is kind of weird IMHO.
Why don't you pass $list in your view?
My problem was in the Controller and in my View,
So I've changed my controller return to
return view ('admin.news.index', [
'results' => $list,
'page' => $page,
'startDate' => $startDate,
'endDate'=>$endDate
] );
And in my view I wasnt calling in a wrong way my parameters...
<tbody>
#if (count($results) > 0)
#foreach ($results as $r)
<tr>
<td>{{ $r->Title }}</td>
<td>{{ $r->Description }}</td>
<td>{{ Carbon\Carbon::parse($r->StartDate)->format('d/m/Y') }}</td>
<td>{{ $r->fileURL }}</td>
<td>{{ Carbon\Carbon::parse($r->RegistedDate)->format('d/m/Y') }}</td>
<td>{{ $r->refCredential }}</td>
</tr>
#endforeach
#else
<tr><td colspan="11">Não existem notícias criadas</td></tr>
#endif
</tbody>

Laravel pagination problem one by one pages

I'm sorry, I have a problem with my laravel pagination Gives me one by one page for example, in my table 16 row I make paginate (10), the pagination gives me in the first page from 1 to 10 and in the second page from 1 to 6 I want the normal pagination from 1 to 10 and from 11 to 16 any help, please
public function allappointmnts(){
$allapo=DB::table('bookappoitments')->orderBy('times.id')
->join('users','bookappoitments.users_id','users.id')
->join('times','bookappoitments.times_id','times.id')
->join('dates','bookappoitments.Dates_id','dates.id')
->paginate(10);
return view('admin.Managers.allappoinments',compact('allapo'));
}
in the blade page:
<div class="text-center">
{!! $allapo->links(); !!}
</div>
The table :
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>#</th>
<th>Date</th>
<th>Time</th>
<th>Employee</th>
<th>Name</th>
<th>Email</th>
<th>Company</th>
<th>Phone</th>
<th>Location</th>
<th>Remarks</th>
<th style="text-align: center;">Action</th>
</tr>
</thead>
<tbody>
<tr>
#foreach($allapo as $Appointments)
<td>{{ $loop->index+1 }}</td>
<td>{{ $Appointments->Dates }}</td>
<td>{{ $Appointments->from_to }}</td>
<td>{{ $Appointments->name }}</td>
<td>{{ $Appointments->gustname }}</td>
<td>{{ $Appointments->gustemail }}</td>
<td>{{ $Appointments->gustcompany }}</td>
<td>{{ $Appointments->gustphone }}</td>
<td>{{ $Appointments->Location }}</td>
<td>{{ $Appointments->Remarks }}</td>
<td>
<a class="btn btn-success btn-mini deleteRecord " href="{{url('showbymanagment',$Appointments->id)}}">Show</a>
</td>
</tr>
#endforeach
Your problem is that you're using the current index of each loop - which will always be within the range of 1-10 of each page (since you have 10 elements per page).
You need to get the current page you're on using
$allapo->currentPage()
Then get the number of elements per page you got, using
$allapo->perPage()
Multiply these two, and it will be the base number for your pagination, meaning that its this number you should increment from.
The indexed table should then be
{{ $allapo->currentPage() * $allapo->perPage() + $loop->index }}
instead of
{{ $loop->index+1 }}
Then, to fix the heading-numbers (10 and 6 at the top), get the total number of results instead of the count of the page using
$allapo->total()
See the Laravel documentation for more details.
Not entirely sure, but you will need to write some sort of function to fix this.
Essentially you need to do this:
Get the page number (ex: 1)
Multiply it by the rows per page (ex: 10)
Add the iteration number
Subtract the per page number
function correct_pagination_numbers($cp, $pp, $counter)
{
$c = (($pp * $cp) + $counter) - $pp;
return $c;
}
Then you can call the function in your view like so:
<td>{{ correct_pagination_numbers($allapo->currentPage(), $allapo->perPage(), $loop->index) }}</td>
It would probably be the best solution to do this in a helper file. If you don't know how to create a helper file and autoload it, you can look here.
Try this code:
<?php $i = $lists->perPage() * ($lists->currentPage() - 1); ?>
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>#</th>
<th>Date</th>
<th>Time</th>
<th>Employee</th>
<th>Name</th>
<th>Email</th>
<th>Company</th>
<th>Phone</th>
<th>Location</th>
<th>Remarks</th>
<th style="text-align: center;">Action</th>
</tr>
</thead>
<tbody>
<tr>
#foreach($allapo as $Appointments)
<td><?php $i++; ?>{{ $i }} </td>
<td>{{ $Appointments->Dates }}</td>
<td>{{ $Appointments->from_to }}</td>
<td>{{ $Appointments->name }}</td>
<td>{{ $Appointments->gustname }}</td>
<td>{{ $Appointments->gustemail }}</td>
<td>{{ $Appointments->gustcompany }}</td>
<td>{{ $Appointments->gustphone }}</td>
<td>{{ $Appointments->Location }}</td>
<td>{{ $Appointments->Remarks }}</td>
<td><a class="btn btn-success btn-mini deleteRecord " href="
{{url('showbymanagment',$Appointments->id)}}">Show</a></td>
</tr>
#endforeach
Try ths
#foreach($allapo as $key => $Appointments)
{{ $key + $allapo->firstItem() }}
#endforeach
to see the correct number change the line
<td>{{ $loop->index+1 }}</td>
to:
<td>{{ ($allapo->currentPage() - 1) * $allapo->perPage() + $loop->iteration }} <td>

Display distinct values on a laravel blade view

I have a prices table that stores the date which a product cost was stored. There is a relationship between the product & price model which works very well by returning the collection. I want to display a table with a date & product name as the columns, then display the DISTINCT dates & the corresponding product cost on each row. Below is my blade view code and what the table looks like
view - code
<table class="table table-striped">
<thead>
<th>Date</th>
#if (isset($products) && !empty($products))
#foreach ($products as $product)
<th>{{ ucwords($product->name) }}</th>
</thead>
<tbody>
#foreach ($product->prices as $price)
<tr>
<td>{{ $price->date }}</td>
<td>{{ $price->cost }}</td>
</tr>
#endforeach
#endforeach
#else
Product price is not available
#endif
</tbody>
</table>
browser-view
Changing my code by ending the first foreach loop, gives me something close to what i want but only the cost for the last product is displayed
alternative code
<table class="table table-striped">
<thead>
<th>Date</th>
#if (isset($products) && !empty($products))
#foreach ($products as $product)
<th>{{ ucwords($product->name) }}</th>
#endforeach
</thead>
<tbody>
#foreach ($product->prices as $price)
<tr>
<td>{{ $price->date }}</td>
<td>{{ $price->cost }}</td>
</tr>
#endforeach
#else
Product price is not available
#endif
</tbody>
</table>
Browser-view
How do i display all of my product cost values for each date in the format of the last picture?

Select List From Database With Parameter

Hi there i have some problem getting list from database using laravel 4.1
I have session that stored some value about companyid. Then i want to print the list to table based on the companyid itself. Let say i can access the session using {{ Session::get('name')}}
This is my controller index()
public function index($cid) {
$pengguna = User::where('id_company', '=', $cid)->get();
$pengguna->toarray();
$data = array(
'pengguna' => $pengguna,
'page' => 'master',
'index' => 0
);
return View::make('console.pengguna')->with($data);
}
then i want to print the data to table in view
#if($pengguna->count())
<table class="table table-striped table-bordered" id="table_pengguna_list">
<thead>
<tr>
<th>No</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Username</th>
<th>Email</th>
<th>Status</th>
<th>Last Login</th>
<th class="td-actions">Action</th>
</tr>
</thead>
<tbody>
#foreach ($pengguna as $pgn)
<tr>
<td>{{ $index++ }}</td>
<td>{{ $pgn->firstname }}</td>
<td>{{ $pgn->lastname }}</td>
<td>{{ $pgn->username }}</td>
<td>{{ $pgn->email }}</td>
<td>{{ $pgn->level }}</td>
<td>{{ $pgn->updated_at }}</td>
</tr>
#endforeach
</tbody>
</table>
....
how to pass the parameter from session to the controller then? so basically pass the {{ Session::get('name')}} to $cid in index controller.
thank you.
hi there i have found the solution, just place refactor the index controller to;
public function index() {
$cid = Session::get('name');
$pengguna = User::where('id_company', '=', $cid)->get();
$pengguna->toarray();
$data = array(
'pengguna' => $pengguna,
'page' => 'master',
'index' => 0
);
return View::make('console.pengguna')->with($data);
}

Categories