Display text on each iteration laravel Livewire - php

I need your help. Lets say I have array with 10 elements and every record to be shown on every iteration and I want to be done with Livewire, let me share with you some code and will tell you what I have tried till now.
public $content;
public $array = ['first', 'second', 'third' ,'fourth'];
foreach ($array as $item) {
sleep(1);
$this->content[] = "Element ${item}";
}
<div class="modal-body">
#if ($content)
<ul class="listree">
#foreach ($content as $element)
<li>
<div class="listree-submenu-heading">
{!! $element['title'] !!}
</div>
<ul class="listree-submenu-items">
#foreach ($element['elements'] as $sub)
<li>
<div class="listree-submenu-heading">
{!! $sub['title'] !!}
</div>
</li>
#endforeach
</ul>
</li>
#endforeach
</ul>
#endif
</div>
My idea is display first record, wait 1 second, display first and second record, wait 1 second, display first, second and third records and so on... How I can do this with livewire. The problem is that $content is filled with the information after all iteration and then the component is refreshed.
I tried on every iteration to send custom event which will call refresh method, but without succes. I will appreaciate any advice, and if you need more information, I will provide it.

Assumming you're also using alpinejs, this can be done pretty easily.
<x-app-layout>
<div class="text-gray-800 ml-10">
<ul class="bg-green-200">
<!-- The main foreach loop. -->
#foreach (range('a', 'z') as $element)
<!-- render al <li> tags with display:none. -->
<!-- Show the 1st after 0s, the 2nd after 1s, the 3rd after 2s, ... -->
<li class="bg-blue-200 m-5"
x-data="{show: false, index: {{ $loop->index }} }"
x-init="setTimeout(() => show = true, index * 1000)">
<div x-show="show">
{{ $element }}
...
</div>
</li>
#endforeach
</ul>
</div>
</x-app-layout>
$loop is a special object you can access within a #foreach block.

Related

How to Handle Blade laravel [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
my controller function is. I passed data through bidder array but array data can't print
public function bidders()
{
$payments = \App\Models\Payment::all();
$posts = Post::all()->where('user_id','=',Auth::user()->id);
foreach ($posts as $post) {
$postid = $post->id;
$bidder[] = Bid::all()->where('post_id','=',$postid);
}
return view('user.student.student-post-bidders',compact('bidder','posts','payments'));
}
Here is my blade in this blade my data print from DB.
How can I print array? indexes of array print in a blade
#php
dd($bidder);
$index = 0;
#endphp
#foreach($bidder as $bid)
#foreach($posts as $post)
#if($post->id == $bid[$index]['post_id'])
<div class="row" >
<!-- Dashboard Box -->
<div class="col-xl-12" >
<div class="dashboard-box margin-top-0">
<!-- Headline -->
<div class="headline">
<h4><strong><span class="bg-danger text-center" style="margin-left: 46px">Your Post Title:</span>{{$bid[$index]->Post->title}}</strong></h4>
</div>
<div class="content">
<ul class="dashboard-box-list">
<li>
<!-- Overview -->
<div class="freelancer-overview manage-candidates">
<div class="freelancer-overview-inner">
<!-- Avatar -->
<div class="freelancer-avatar">
<div class="verified-badge"></div>
#if($bid[$index]->Tutor->profile_Image=='')
<img data-cfsrc="{{asset('asset/images/user-avatar-placeholder.png')}}" alt="" style="display:none;visibility:hidden;">
#else
{{-- {{asset('storage/app/public/profileImages/' . $pic->profile_Image)}}--}}
<img data-cfsrc="{{asset('storage/app/public/profileImages/' . $bid[$index]->Tutor->profile_Image)}}" alt="" style="display:none;visibility:hidden;">
#endif
</div>
<!-- Name -->
<div class="freelancer-name">
<h4>{{$bid[$index]->Tutor->name}}</h4>
<!-- Details -->
<strong><span>Subject:</span></strong>
#foreach($bid[$index]->Tutor->subject as $sub)
<strong><span>{{\App\Models\Subject::find($sub->pivot->subject_id)->subject}}</span></strong>
#endforeach
<!-- Rating -->
<div class="freelancer-rating">
<div class="star-rating" data-rating="{{$bid[$index]->Tutor->rating}}"></div>
</div>
<!-- Bid Details -->
<ul class="dashboard-task-info bid-info">
<li><strong id="{{ $bid[$index]->id}}">PKR:{{$bid[$index]->bid_price}}</strong><span>Fixed Price</span></li>
<li><strong>Days:{{$bid[$index]->days}}</strong><span>Delivery Time</span></li>
</ul>
<!-- Buttons -->
<div class="buttons-to-right always-visible margin-top-25 margin-bottom-0" onclick=" indexID({{$i}})">
<a href="#small-dialog-1"
onclick="moveprice({{ $bid[$index]->id}}), payment({{ $bid[$index]->id}})" class="popup-with-zoom-anim button ripple-effect"
#foreach($payments as $pay) #if($bid[$index]->post_id == $pay->post_id) id="hide" #endif #endforeach><i class="icon-material-outline-check "></i> Accept Bid</a>
{{-- #dd($bid->id)--}}
<i class="icon-feather-mail"></i> Send Message
<a id="btn" class="button gray ripple-effect ico" onclick="removeBid({{$bid[$index]->id}})" title="Remove Bid" data-tippy-placement="top"><i class="icon-feather-trash-2"></i></a>
</div>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
<span style="visibility: hidden">{{$i++}}</span>
#endif
#endforeach
#php
$index++;
#endphp
#endforeach
When I run code error will be occur
offset 1 I need all data print in a blade
How to print array index wise
you should use relations,
if you want to show the list of bidders then in bidders model
app/bidders.php
public function post()
{
return $this->belongsTo('App\Post');
}
Assuming that you have proper standards in table structure for mapping eloquent.
then you need to change your bidders function as below
public function bidders()
{
$payments = \App\Models\Payment::get();
$bidders = Bidder::whereHas('post', function($post) {
return $post->where('user_id','=',Auth::user()->id);
//Provides a filter for bidders, post which are related to user
})->with('post')->get();
return view('user.student.student-post-bidders',compact('bidders', 'payments'));
}
And there should be only one loop for bidders on blade as below.
Here is your answer why array is not appearing in blade check in comments for json_encode
#foreach($bidders as $bid)
{{$bid->id}} //gives you bid parameters
{{json_encode($bid->post)}} //this will get all the post details array/object is not printable on blade so encoded to json just for display purpose
//suppose you need only name from post then
{{$bid->post->name}};
#endforeach
This will lower your code length, as well as improve performance due to eager loading and less looping. Also removes stuff like creating array and maintain index and if condition on blade for id check.
That's it.
Happy Coding!!
I think you just need to refactoring your code ),
first of all use $bid->{$index} instead of this $bid[$index]. you have collection but you can use it as array
do you want to group your bidder by post_id ?

Get property of an object

I have a one to many model.
An WorkoutDetails which has many Exercises.
I was able to display all the data for the Exercises, but I need just the property 'Title'.
In controller I have
public function getDetails($id){
$details = WorkoutDetails::where('parent_id','=',$id)->get();
return View::make('menu_renderer.partials.details')->with('details', $details);
}
And in HTML I have
#foreach($details as $detail)
<div>
<ul>
{{$detail->exercises}}
</ul>
</div>
#endforeach
And the output is:
[{"id":1,"type_id":0,"title":"Exercise one","details":"Details
exercise one","media":"5","created_at":"-0001-11-30
00:00:00","updated_at":"-0001-11-30 00:00:00"}]
[{"id":2,"type_id":0,"title":"Exercise two","details":"Details
exercise two","media":"2","created_at":"-0001-11-30
00:00:00","updated_at":"-0001-11-30 00:00:00"}]
[{"id":3,"type_id":0,"title":"Exercise three","details":"Details
Exercise three","media":"6","created_at":"-0001-11-30
00:00:00","updated_at":"-0001-11-30 00:00:00"}]
[{"id":4,"type_id":0,"title":"Exercise four","details":"Details
Exercise four","media":"6","created_at":"-0001-11-30
00:00:00","updated_at":"-0001-11-30 00:00:00"}]
Which is not bad, but I need just the title or details.
I tried
#foreach($details as $detail)
<div>
<ul>
{{$detail->exercises->title}}
</ul>
</div>
#endforeach
or
#foreach($details as $detail)
<div>
<ul>
{{$detail->exercises.title}}
</ul>
</div>
#endforeach
or
#foreach($details as $detail)
<div>
<ul>
{{$detail->exercises[title]}}
</ul>
</div>
#endforeach
But nothing...
Can anyone give me a hint how can I display just the title or details of each Exercise which belongs to WorkoutDetails model ?
Thank you!
From the dump provided, it seems another array is holding the inner data.
hence try :
#foreach($details as $detail)
<div>
<ul>
{{$detail->exercises[0][title]}}
// or :
{{$detail->exercises[0]->title}}
</ul>
</div>
#endforeach
You can use laravel query function first() to pickup the first object.
#foreach($details as $detail)
<div>
<ul>
{{ $detail->exercises->first()->title }}
</ul>
</div>
#endforeach

Multi-level menu in laravel 5.1 - loops

I am a little bit new with laravel 5.1 framework. Last couple of days I create my database (insert, update, delete) for dynamic menu I want to create. I connect with default layout in which i put menu. From route code looks like this.
View::composer('layouts.default',function($view){
$menus = Menu::where('parent_id',0)->orderBy('order')->get();
$submenus = Menu::where('parent_id','!=',0)->get();
$view->with(compact('menus','submenus'));
});
In main menu are items with parent_id = 0. Submenu items have parent_id = id, and soo on.
I want to display correct but when I hover main menu items that dont have items, css block appear, becouse i didnt make good if condition. Is there any way to do this?
Code in view look like this.
#foreach($menus as $menu)
<li class="dropdown {!! (Request::is('typography') || Request::is('advancedfeatures') || Request::is('grid') ? 'active' : '') !!}"> {!! $menu->title !!}
<ul class="dropdown-menu" role="menu">
#foreach($submenus as $submenu)
#if($submenu->parent_id === $menu->id)
<li>{!! $submenu->title !!}
#foreach($submenus as $smenu)
#if($smenu->parent_id === $submenu->id)
<ul class="dropdown-submenu" role="menu">
<li>{!! $smenu->title !!}
</li>
</ul>
#endif
#endforeach
</li>
#endif
#endforeach
</ul>
</li>
#endforeach
One more question is how to take only one value from Menu model for example id that can be used to point only one submenu.
Best regards!
You can do it simply by using recursion. I removed html classes for readability.
Note: Set NULL parent_id for root items.
Add this relation to your Menu Model.
function childs()
{
return $this->hasMany('Namespace\Menu','parent_id', 'id');
}
In your controller get the menus who has no parent.
$menus = Menu::whereNull('parent_id')->orderBy('order')->get();
Then display them in your view.
<ul>
#foreach($menus as $menu)
<li>
{!! $menu->title !!}
#include('childItems')//recursion view
</li>
#endforeach
</ul>
And this is what your childItems.blade.php will look like.
<ul>
#foreach($menu->childs as $menu)
<li>
{!! $menu->title !!}
#include('childItems')//call itself for deeper relations.
</li>
#endforeach
</ul>
That's it.

Included blade template repeating in each foreach loop iteration

I'm using Blade templating with Laravel and I'm trying to use a #foreach loop to display notifications. The problem is that if I have say 10 notifications, the first notification is repeated 10 times.
The code to output each notification:
#foreach ( Auth::user()->unreadNotifications as $notification )
{{ $notification->type->web_template }}
{{ $notification->id }}
#include($notification->type->web_template)
#endforeach
web_template will output a path to the template: notifications.web.user_alert
For each iteration of the loop the {{ $notification->type->web_template }} and {{ $notification->id }} will output what they're supposed to but #include($notification->type->web_template) will only output the first notification each time.
So the output will look like:
156 notification.web.new_message
You have a new message from Joe.
154 notification.web.user_alert
You have a new message from Joe.
145 notification.web.new_like
You have a new message from Joe.
I think it's some sort of cache issue maybe, but I couldn't find anyone with the same problem.
Any ideas?
UPDATE: Adding some code
Example notification view:
#extends('layouts.notification-wrapper')
#section('url', url('jobs/'.$notification->job_id.'#highlight'.$notification->bid_id))
#section('image', '/assets/img/no-photo.jpg')
#section('header', $notification->collector->firstname . ' ' . $notification->collector->secondname)
#section('description')
has placed a bid of €{{ number_format($notification->bid()->withTrashed()->first()->amount,0) }} on your job.
#stop
Notification wrapper:
<li #if(!$notification->read)
class="unread"
#endif>
<a href="#yield('url')" data-id="{{ $notification->id }}">
<div class="pull-left">
<img src="#yield('image')" class="img-circle" alt="user image">
</div>
<h4>
#yield('header')
<small><i class="fa fa-clock-o"></i> {{ $notification->created_at->diffForHumans()}}</small>
</h4>
<p> #yield('description')</p>
</a>
</li>
Answering my own question!
Found this: Laravel Blade Templates Section Repeated / cache error
Basically whatever way it works I need to overwrite my sections when looping and using #yield... I think. So I need to replace #stop with #overwrite in my views.

Iterating over PHP array with Laravel Blade, and then adding in HTML for columns

I have an array with 38 records.
After iterating over the first 10 I want it to start on a new column.
This is very simple and an example is below, however, I need to add in HTML which makes it difficult:
#for($i = 0; $i < count($records); $i++)
#if($i % 10 == 0)
//start new column
#endif
<li>{{ $records[$i]['name'] }}</li>
#endfor
What the HTML looks like without looping and what it should look like after looping properly:
<li class="col-sm-3">
<li class="dropdown-header">
Record Set
</li>
<li>Record Name</li>
<li>Record Name</li>
<li>Record Name</li>
</li>
Problem is, after 10 records I need it to break out of col-sm-3 and start a new col-sm-3 without the dropdown-header but with each iteration's record name.
How can this be done? Please ask questions if clarification is needed.
If it's an array then you may use array_chunk:
#foreach(array_chunk($records, 10) as $ten_arrays)
<li class="col-sm-3">
#foreach($ten_arrays as $record)
{{ $record['field_name'] }}
#endforeach
</li>
#endforeach
This will output lis like this:
<li class="col-sm-3">
<!-- Ten Items -->
</li>
<li class="col-sm-3">
<!-- Ten Items -->
</li>

Categories