Undefined variable: products in #foreach - javascript

I'm facing some issues with a project build with Laravel
i want to show more then 12 product but i don't know what to change. this show only 12 product and i want 60 product to show. please help me. I've tried many solutions but its not working.
<div class="products-box-bar p-3 " >
<div class="row sm-no-gutters gutters-5">
#foreach ($products as $product)
<div class="col-xxl-3 col-xl-4 col-lg-3 col-md-4 col-6" >
<div class="product-box-2 bg-white alt-box my-md-2" style="border: 1px solid #f1f1f1;border-radius: 8px;">
<div class="position-relative overflow-hidden">
<a href="{{ route('product', $product->slug) }}" class="d-block product-image h-100 text-center" tabindex="0">
<img class="img-fit lazyload" src="{{ asset('frontend/images/placeholder.jpg') }}" data-src="{{ asset($product->thumbnail_img) }}" alt="{{ __($product->name) }}">
</a>
<div class="product-btns clearfix">
<button class="btn add-wishlist" title="Add to Wishlist" onclick="addToWishList({{ $product->id }})" type="button">
<i class="la la-heart-o"></i>
</button>
<button class="btn add-compare" title="Add to Compare" onclick="addToCompare({{ $product->id }})" type="button">
<i class="la la-refresh"></i>
</button>
<button class="btn quick-view" title="Quick view" onclick="showAddToCartModal({{ $product->id }})" type="button">
<i class="la la-eye"></i>
</button>
</div>
</div>
<div class="p-md-3 p-2">
<h2 class="redbaba">
<a href="{{ route('product', $product->slug) }}" class="product-title p-0 text-truncate-2" >
#if(home_base_price($product->id) != home_discounted_base_price($product->id))
<img class="sale654" src="{{ route('home') }}/ufo/img/sale.png"></img>
#endif
{{ __($product->name) }}
</a>
</h2>
<div class="price-box">
<span class="product-price strong-600" style="display: block;">{{ home_discounted_base_price($product->id) }}</span>
#if(home_base_price($product->id) != home_discounted_base_price($product->id))
<del class="old-product-price strong-400">BDT {{ home_base_price($product->id) }}</del>
#if (\App\Addon::where('unique_identifier', 'club_point')->first() != null && \App\Addon::where('unique_identifier', 'club_point')->first()->activated)
<span class="clubpoint02">⛬ Point {{ $product->earn_point }}</span>
#endif
#endif
</div>
<h2 class="djhfgj">
{{ __($product->shipping_type) }} shipping
</h2>
<div class="star-rating star-rating-sm mt-1" >
{{ renderStarRating($product->rating) }}
</div>
<p class="numberofsale">{{ __($product->num_of_sale) }} Sold</p>
</div>
</div>
</div>
#endforeach
</div>
</div>
<nav aria-label="Center aligned pagination" >
<ul class="pagination justify-content-center" style="background-color: #fff;padding: 10px 0;border-radius: 10px;margin-top: 15px;">
{{ $products->links() }}
</ul>
</nav>

In your App\Http\ProductsController.php or whichever file you use in fetching products from the database, you should see a function paginate(12), change it to paginate(60)

The title of your post is a little confusing as it doesn't match your description, I'll do my best to help though!
Undefined Variable: $products
This will most likely be due to the controller not passing a variable to the blade template.
In your controller, make sure that you are passing the variables to the view like so:
public function index() {
// Your logic here
return view('my-index', [
'products' => $products
]);
}
Pagination Limits
Displaying 12 items rather than 60 will be due to the limits passed to the paginate() function within the controller. Make sure you have set this to 60
public function index() {
// Retrieve up to 60 products at a time
$products = Product::paginate(60);
return view('my-index', [
'products' => $products
]);
}
Forelse loops
You may want to consider using a #forelse loop rather than a #foreach loop in case you don't have any products being returned from the query
#forelse($products as $product)
// Display your products
#empty
// Display a message saying no products were found
#endforelse

Related

How to display the results based on their parent selection in angular 8

I am trying to display only the corresponding items on selection of its parent (similar to if country is selected then its corresponding states should display) for that i have this below code but the problem is i am not able to apply the filtering. Can anybody help me resolve in this?
See the code below: (The below code is for first tile on selection of this i am showing below its corresponding account related data)
<div class="col mb-3" *ngFor="let account of cloudAccounts1">
<a href="javascript:;" class="item-card text-dark mat-elevation-z8">
<div class="text-center" (click)="getInstances($event, account)"
[ngClass]="{'bg-info text-white': entry.account == account}">
<div class="card-header py-3">
<div *ngIf="account.accountType === 'AZURE'">
<img class="img-responsive h-25 w-25" src="assets/images/azure.png" />
</div>
<div *ngIf="account.accountType === 'AWS'">
<img class="img-responsive h-25 w-25" src="assets/images/aws.png" />
</div>
<div *ngIf="account.accountType === 'GCP'">
<img class="img-responsive h-25 w-25" src="assets/images/gcp.png" />
</div>
<div class="mt-2"> {{account.accountType}}</div>
</div>
<div class="card-footer no-border py-3">
<div class="text-truncate">{{account.name}}</div>
</div>
</div>
</a>
</div>
The below code is for which when i select any of the above account say AWS or AZURE or GCP then only its corresponding tile should display. The below code.
<div class="col-md-2" *ngIf="showRegion">
<br />
<div class="h6">Instance Type</div>
<div class="row">
<div class="col mb-3" *ngFor="let account of cloudAccounts2">
<a href="javascript:;" class="item-card text-dark mat-elevation-z8">
<div class="text-center">
<div class="card-header py-3">
<div *ngIf="account.accountType === 'AWS'">
<img class="img-responsive h-25 w-25" title="{{account.name}}"
src="assets/images/aws.png">
<div>{{account.accountType}}</div>
</div>
<div *ngIf="account.accountType === 'AZURE'">
<img class="img-responsive h-25 w-25" title="{{account.name}}"
src="assets/images/azure.png">
<div>{{account.accountType}}</div>
</div>
<div *ngIf="account.accountType === 'GCP'">
<img class="img-responsive h-25 w-25" title="{{account.name}}"
src="assets/images/gcp.png">
<div>{{account.accountType}}</div>
</div>
</div>
<div class="card-footer py-3 no-border text-truncate">{{account.name}} <i class="fa fa-external-link" aria-hidden="true"></i></div>
</div>
</a>
</div>
</div>
In cloudAccounts2 array, i have this data, i need to show only one tile on selection of its parent account. But instead its showing all 3 tiles which i dont want.
cloudAccounts1 = [{ "id": "8a8080fc710cdc140171104216c2002b", "accountType": "AWS" },
{ "id": "8a8080fc710cdc140171104216c2002b", "accountType": "AZURE" },
{ "id": "8a8080fc710cdc140171104216c2002b", "accountType": "GCP" }]
Based on the above selection i need to display only its corresponding below data.
cloudAccounts2 = [{"accountType":"AWS", "name":"T2.micro", "link":"https://aws.amazon.com/ec2/pricing/on-demand/"},
{"accountType":"AZURE", "name":"STANDARD_A1", "link":"https://azure.microsoft.com/en-us/pricing/details/virtual-machines/linux/"},
{"accountType":"GCP", "name":"n1-standard-1", "link":"https://cloud.google.com/compute/vm-instance-pricing"}
];
This is the method where i am handling the logic to display only the selected values to display in the template. Can anybody let me know what is my mistake?
getInstances(event, instanceSelected) {
this.classToggled = false;
this.entry.account = instanceSelected;
if(this.entry.account.accountType === instanceSelected.accountType){
this.showInstance = true;
// this.cloudAccounts2 = [];
// this.cloudAccounts2 = [instanceSelected];
if(instanceSelected.accountType === this.cloudAccounts2[1].accountType){
this.cloudAccounts2[1].accountType = instanceSelected.accountType;
}
}
}
It looks like you are trying to do an NgIf within a loop to select your item. Instead of doing that you can create new objects for your selected account (see component) and instead of getInstances() on click do selectAccount1()
Html:
<div *ngFor="let account of cloudAccounts1">
<a (click)="selectAccount1(account)">
...
</a>
</div>
<div *ngFor="let account of cloudAccounts2">
<a (click)="selectAccount2(account)">
...
</a>
</div>
<div *ngIf="selectedAccount1">
<ul>
<li>id: {{ selectedAccount1.id }}</li>
<li>accountType: {{ selectedAccount1.accountType }}</li>
</ul>
</div>
<div *ngIf="selectedAccount2">
<ul>
<li>accountType : {{ selectedAccount2.accountType }} </li>:
<li>name: {{ selectedAccount2.name }}</li>
<li>link: {{ selectedAccount2.link }}</li>
</ul>
</div>
Component:
public selectedAccount1: any;
public selectedAccount2: any;
public selectAccount1(account: any): void {
this.selectedAccount1 = account;
}
public selectAccount2(account: any): void {
this.selectedAccount2 = account;
}

Cannot read property 'submit' of null i use laravel and javascript

I want to add a product to my favorites, but I do not want to make a load for the entire page, so I use JavaScript as shown in the code where I made an ancor disruption and created a form and took an id from the form and implemented it by using the submit function, but the following error appears and does
Uncaught TypeError: Cannot read property 'submit' of null
Please advise the importance
Thank you
this view
<div class="product-info">
<div class="tab-content" id="myTabContent">
<!-- Start Single Tab -->
<div class="tab-pane fade show active" id="man" role="tabpanel">
<div class="tab-single">
<div class="row">
#foreach($products as $p)
<div class="col-xl-3 col-lg-4 col-md-4 col-12">
<form action="{{route('cart.store')}}" method="post" id="add-cart-{{$p->id}}">
{{ csrf_field() }}
<input type="hidden" name="id" value="{{$p->id}}">
<input type="hidden" name="Product_Name_ar" value="{{$p->Product_Name_ar}}">
<input type="hidden" name="Price" value="{{$p->Price}}">
<div class="single-product">
<div class="product-img">
<a href="{{route('product', ['product' => $p->id])}}">
<img class="default-img" src="{{ asset('images/products/'.$p->image) }}" alt="#">
<img class="hover-img" src="{{ asset('images/products/'.$p->image) }}" alt="#">
</a>
<div class="button-head">
<div class="product-action">
#if(Auth::guard('customer')->check())
<span class="favorite-count">{{ $p->favorite_to_customers->count() }}</span>
<a title="Wishlist" href="javascript:void (0);" onclick="document.getElementById('favorite-{{$p->id}}').submit()" class="{{ Auth::guard('customer')->user()->favorite_products()->where('product_id', $p->id)->count() != 0 ? 'favorite' : '' }}">
<i class="fa fa-heart "></i><span>Add to Favorite</span></a>
<form id="favorite-{{$p->id}}" action="{{route('product.favorite', $p->id)}}" method="post">
{{ csrf_field() }}
</form>
#else
<span class="favorite-count">{{ $p->favorite_to_customers->count() }}</span>
<a title="Wishlist" href="javascript:void (0);" onclick="toastr.info('To add favorite list you to need login first', 'info', {
closeButton: true,
progressBar: true
})">
<i class="fa fa-heart "></i>
<span>Add to Favorite</span></a>
#endif
</div>
<div class="product-action-2">
<button style="background: transparent; border: none; color: black" class="btn btn-warning">Add to chart</button>
</div>
</div>
</div>
<div class="product-content">
<h3>{{ $p->Product_Name_ar }}</h3>
<div class="product-price">
<span>{{ $p->Price }} K.D</span>
</div>
</div>
</div>
</form>
</div>
#endforeach
</div>
</div>
</div>
<!--/ End Single Tab -->
</div>
</div>
This Controller
class Favoritecontroller extends Controller
{
public function add($id) {
$customer = Auth::guard('customer')->user();
$isFavorite = $customer->favorite_products()->where('product_id', $id)->count();
if($isFavorite == 0) {
$customer->favorite_products()->attach($id);
}else {
$customer->favorite_products()->detach($id);
}
return redirect()->back();
}
}
This Route
Route::group(['middleware' => ['auth:customer']], function () {
Route::post('favorite/{id}/add', 'FavoriteController#add')->name('product.favorite');
});
I assume your JS fails here
... onclick="document.getElementById('favorite-{{$p->id}}').submit()"
The proper way to do it
... onclick="addToWhishList({{$p->id}})"
Then in your JS
<script>
function addToWhishList(formId) {
//console.log(formId);
document.getElementById('favorite-' + formId).submit();
}
</script>
Check working Demo

how to stop iterating my like button inside my post

I am working on a post system with likes where the user can toggle the post`s like I have done everything correctly except the last step, the problem inside my v-for loop I fetch likes table from post-like relation(many to many since likes table has user_id and post_id) but it is iterating my button even when I add a condition look here-> duplicated like button, I have tried many things v-if, v-show I think the problem is with my algorithm I hope someone can fix that for me thanks.
<div class="panel panel-white post panel-shadow" v-for="post in posts" >
<div class="post-heading">
<div class="pull-left image">
<img v-bind:src="'img/profile/' + post.user.photo" class="img-circle avatar" alt="user profile image">
</div>
<div class="pull-left meta">
<div class="title h5">
<b>{{post.user.name}} </b>
made a post.
</div>
<h6 class="text-muted time">{{post.created_at | hour}}</h6>
</div>
</div>
<div class="post-description">
<p>{{post.content}}</p>
<div class="stats">
<button class="btn btn-default stat-item" #click.prevent="addLike(post.id)">
<i class="fa fa-thumbs-o-up" aria-hidden="false" style="color: blue" v-for="(like) in post.likes" v-bind:style="like.user_id===id && like.post_id===post.id?'color: blue;':'color: gray;'" > Like {{post.likes.length}}
</i> <!-- here is the duplicate problem-->
</button>
<a class="btn btn-default stat-item" #click.prevent>
<i class="fa fa-reply-all"> {{post.comments.length}}</i> Comments
</a>
</div>
</div>
<comment-input :post="post" :userId="id" :userPhoto="userPhoto"></comment-input>
<ul class="comments-list" v-for="comment in post.comments?post.comments:''">
<comments :comment="comment" :userId="id" :userPhoto="userPhoto"></comments>
</ul>
</div>
<hr>
</div>
</div>
Don't loop through the button element, try to use a method likedBythisUser to check if the current user liked the post in order to bind it to the button style :
methods:{
likedBythisUser(post,id){
return post.likes.find(like=>{
return like.user_id===id && like.post_id===post.id;
}) // return a boolean value
}
}
template :
<button class="btn btn-default stat-item" #click.prevent="addLike(post.id)">
<i class="fa fa-thumbs-o-up" aria-hidden="false" style="color: blue" bind:style="likedBythisUser(post,id)?'color: blue;':'color: gray;'" > Like {{post.likes.length}}
</i> <!-- here is the duplicate problem-->
</button>

String interpolation with angular not binding

I'm trying to bind the data to a template using string interpolation. When I am trying to refer the variable in the template, then it returns the following error:
core.js:1350 ERROR TypeError: Cannot read property 'status' of
undefined.
HTML code:
<div class="chat-main">
<div class="col-md-12 chat-header rounded-top bg-primary text-white hide-chat-box">
<div class="row">
<div class="col-md-6 username pl-2">
<h6 class="m-0"> Tasks</h6>
<span class="badge" style="background: red">{{ task?.status?.length }}</span>
</div>
<div class="col-md-6 options text-right pr-2">
<i class="fa fa-window-minimize" aria-hidden="true"></i>
</div>
</div>
</div>
<div class="chat-content">
<div class="col-md-12 chats border">
<br/>
<ul class="p-0" *ngFor="let task of tasksRes">
<li class="pl-2 pr-2 text-dark send-msg mb-1">
<div>
<a href="javascript:;" [routerLink]="[task.link]" style="text-decoration: none !important;">
<span class="text-warning" *ngIf="task.status == 'In_progress'"><i class="fa fa-spinner fa-spin"></i></span>
<span class="text-success" *ngIf="task.status == 'Done'"><i class="fa fa-check"></i></span>
<span> {{ task.name }}</span>
</a>
<br/>
<span class="pull-right text-muted">{{task.createdDate | timeAgo}}</span>
<span class="text-muted"> {{task.eventType}}</span>
</div>
</li>
</ul>
</div>
</div>
</div>
task is local variable scope only inside ngFor template that mean ul element here
just move this span element to be inside `ngFor' template
<span class="badge" style="background: red">{{ task?.status?.length }}</span>
NgFor Local Variables

Alternate Image/text position in foreach loop dynamic data

So I am displaying two blocks of data in a tile format using bootstrap I can have two halves of a row. In this case on the right I have an image, on the left I have a div which displays text and buttons. I intend to have the even rows have the image on the left and odd on the right. So basically an image will always be on top and under text. Alternating in each row the divs will be mirrored.
Using javascript, blade, php or css how could i achieve this effect?
#foreach ($offers as $offer)
<div class="offersNew">
<div class="row row-equal-height">
<div class="col-md-6 paddedCol6">
<div class="inner">
<h2 class="centered marginTop0">{{ $offer->title or 'No title' }}</h2>
<h3 class="sub-header centered">{{ $offer->sub_header or '' }}</h3>
<p class="centered">
{{ mb_strimwidth(strip_tags($offer->homepage_description), 0, 200, '...') }}
</p>
<div class="callToAction">
<center>
<a href="/offer/{{ $offer->slug or $offer->id }}">
<button class="buttonOne"><p class="sub-header line0 margin1 white smallerText"> Let&apos;s Go! </p></button>
</a>
<a href="/offer/{{ $offer->slug or $offer->id }}">
<button class="buttonTwo"><p class="sub-header line0 margin1 blue smallerText">Other Offers</p></button>
</a>
</center>
</div>
#if ($offer->countdown == 1)
<div class="row countdown" data-timer="{{ $offer->end }}">
<h2 class="sub-header centered">
<span class="blueText">OFFER END</span>
<span class="days">0</span>:
<span class="hours">0</span>:
<span class="minutes">0</span>:
<span id="seconds"></span>
<span id="offerEndtime">0</span>
</h2>
</div>
#endif
</div>
</div>
<div class="col-md-6 main-background hidden-sm hidden-xs max400" style="background-image:url('{{ $offer->image or '' }}')">
</div>
</div>
</div>
#endforeach
Add a count variable and use modulus to alternate.
$count = 0;
foreach($offers as $offer){
if($count % 2 == 0){
// show variation 1
}else{
// show variation 2
}
$count++;
}

Categories