increment row number with laravel pagination - laravel

How to make increment row number with laravel pagination ? When i use pagination and i go to page 2 and above it will back to beginning. for example i will paginate(3)
<thead>
<tr>
<th>No</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<?php $i = 1; ?>
#foreach ($telephone->results as $telp)
<tr>
<td>
{{$i++}}
</td>
<td>{{ $telp->name }}</td>
</tr>
#endforeach
</tbody>
when i go to page 2 the number will start from 1 again.
i need to make it when i go to page 2 it will start from 4

In Laravel 5.3 you can use firstItem():
#foreach ($items as $key => $value)
{{ $items->firstItem() + $key }}
#endforeach

The below works with laravel 5.4
<?php $i = ($telephone->currentpage()-1)* $telephone-
>perpage() + 1;?>
#foreach($telephone as $whatever)
<td> {{ $i++ }}</td>
#endforeach
Edited
The below works for laravel 5.7 above
#foreach ($telephone as $key=> $whatever)
<td>{{ $key+ $telephone->firstItem() }}</td>
#endforeach

You should be able to use the getFrom method to get the starting number of the current pages results. So instead of setting $i = 1; you should be able to do this.
<?php $i = $telephone->getFrom(); ?>
In Laravel 3 there is no getFrom method so you need to calculate it manually.
<?php $i = ($telephone->page - 1) * $telephone->per_page + 1; ?>

Laravel 5.3
#foreach ($products as $key=>$val)
{{ ($products->currentpage()-1) * $products->perpage() + $key + 1 }}
#endforeach

For Laravel 6.2:
$loop - just in case, is a built-in instance in Blade
#foreach($array as $item)
<tr class="table-row">
<td class="site-id">
{{($array->currentPage() - 1) * $array->perPage() + $loop->iteration}}
</td>
</tr>
#endforeach
</table>

You can simply add the following line
$i = ($telephone->currentpage()-1)* $telephone->perpage();
in place of
$i = 1;

#php($sl = ($yourVariable->perPage() * $yourVariable->currentPage()) - ($yourVariable->perPage() - 1))
#foreach($yourVariable as $item)
<td>{{ $item->key_name }}</td>
.....
#php($sl++)
#endforeach

In Laravel 6
#php $i = ($data->currentpage()-1)* $data->perpage() + 1;#endphp
#foreach($data as $banner)
<tr>
<td>{{$i}}</td>
<td><img src="{{ URL::to('/') }}/dist/img/{{$banner->name}}" height="250" width="600"></td>
</tr>
#php $i += 1; #endphp
#endforeach

If you are using Laravel Pagination. It works very well
The backend
public function index()
{
return view('your.telephone.index', [
'telephone' => Telephone::paginate(15)
]);
}
Blade front end
<td>{{ (($telephone->currentPage() * 10) - 10) + $loop->iteration }}</td>
And don't forget embed the page
{{ $telephone->links() }}
For $loop->iteration
See the doc here: https://laravel.com/docs/7.x/blade#the-loop-variable
For $telephone->currentPage()
See the doc here: https://laravel.com/docs/7.x/pagination#paginator-instance-methods

Or avoid php tags completely by
#foreach ($users as $key => $user)
{{ (Input::get('page', 1) - 1) * $users->getPerPage() + $key + 1 }}
#endforeach

You can use it in your controller. example given below
$records = Table::paginate(20);
return view('yourview',compact('records')->with('i', ($request->input('page', 1) - 1) * 20);
Note: paginate value must be equal to with() function vlaue
after that you can use $i variable in you blade file. controller calculate value according to page number and return to blade
In blade file. use inside the loop
{{ ++$i }}
Hopefully this will help you

Laravel 8++
$loop->iteration is available out of the box inside loop.
{{ ($barangs->currentPage() - 1) * $barangs->count() + $loop->iteration }}

I'm using this, in Laravel 8, accessing $loop, and links()->paginator:
#foreach ($users as $user)
<tr>
<td class="text-center">{{ ($users->currentPage() - 1) * $users->links()->paginator->perPage() + $loop->iteration }}</td>
<td class="text-center">{{$user->name}}</td>
</tr>
#endforeach
Which works properly even when the final page is only partially filled.
Could also use $users->perPage() in place of $users->links()->paginator->perPage()

Related

Foreach inside Foreach based on column value

I have an sql table knowledgebase like so
id , categoryid, title
id
categoryid
title
1
1
apple
2
1
fb
3
2
google
4
2
DB
5
3
Reebok
In my laravel blade, I am trying to create a tree view to look like the following
-1
--apple
--FB
-2
--google
--DB
-3
--Reebok
My controller does a basic query and returns the entire table to the view. I am a newbie to laravel so far, I can get a basic table to work like
#foreach($knowledgebase as $key => $value)
<tr>
<td>{!! $knowledgebase ->id !!}</td>
<td>{!! $knowledgebase ->title!!}</td>
<td>{!! $knowledgebase ->categoryid !!}</td>
</tr>
#endforeach
How would I iterate categroyid column , display first category and all child titles and then move on to the next categoryid.
Update
public function show($id) {
//get article
$knowledgebase = \App\Models\Knowledgebase::Where('knowledgebase_slug', request('knowledgebase_slug'))->first();
return view('knowledgebase', compact('knowledgebase'));
}
You will need to retrieve in controller the categories before ($categories)
#foreach($categories as $category)
<tr>
<td>{{ $category->id }}</td>
<td>{{ $category->title}}</td>
<td>{{ $category->categoryid }}</td>
</tr>
#endforeach
Anyways, I managed to solve this by adding a function children in my model. So in my Model added
public function children(){
return $this->hasMany('App\Models\Knowledgebase', 'categoryid');
}
After this, I simply called it as a foreach inside my foreach
#foreach($categories as $category)
<li>{{ $category->title}}</li>
#if($category->children)
#foreach($category->children as $child)
<ul>
<li class="pl-3"> {{ $child->title}} </li>
</ul>
#endforeach
#endif
#endforeach

Get sum of minutes of specific project

I want to get total minutes. Example: joylinkhk 240 + 180 = 420. How can I get a total minute of a specific user?
controller
public function search(Request $request) {
$date = explode(' - ', $request->date);
$auth = Auth::user();
$hourLog = Hourlog::with('project', 'user');
if ($auth->user_type == 1) {
$hourLog->where("user_id", $auth->id);
}
$data = [
"date" => $date,
// 'projects' => Project::whereIn('id', $request->project)->get(),
'projects' => Project::with('users')->whereIn('id', $request->project)->get(),
'users' => User::with(['hourlog' => function ($query) use ($request) {
$query->whereIn('project_id', $request->project);
}])->whereIn('id', $request->user)->get(),
];
return view('cms.projectreport.projectreport-list', $data);
}
HTML view
#foreach($users as $user)
<tr>
<td>{{$user->name}}
</td>
#foreach($user->hourlog as $hourlogs)
<td>{{$hourlogs->hour_work}}
</td>
#endforeach
</tr>
#endforeach
Laravel collections are very powerful and offer such functionality out of the box.
Below is a example of how you can take a collection of arrays and sum by its property hour_work. The collect function is a quick way to create a collection like the $user->hourlog already is.
collect([
['hour_work' => 198],
['hour_work' => 93],
['hour_work' => 51],
['hour_work' => 112],
])->sum('hour_work');
// Result: 454
As #danny-van-der-sluijs said, you can use sum on a collection
#foreach($users as $user)
<tr>
<td>{{$user->name}}</td>
#foreach($user->hourlog as $hourlogs)
<td>{{$hourlogs->hour_work}}</td>
#endforeach
</tr>
#endforeach
<tr>
<td>Grand Total</td>
<td>{{ $users->sum(fn($user) => $user->hourlog->sum('hour_work')) }}</td>
</tr>
Note:
$users->sum(fn($user) => $user->hourlog->sum('hour_work'))
Is an arrow function that came with php 7.4, If you are using a version below 7.4 you have to do it like this
$users->sum(function($user) {
return $user->hourlog->sum('hour_work');
});
You can sum in foreach loop, but get the result outside of foreach loop. You need to define first the variable outside of foreach $sum_total = 0;, then you can sum inside foreach like this :
<?php $sum_total = 0; ?> // define here
#foreach($users as $user)
<tr>
<td>{{$user->name}}
</td>
#foreach($user->hourlog as $hourlogs)
<td>{{$hourlogs->hour_work}}
</td>
<?php
$sum_total += (intval)$hourlogs->hour_work
?>
#endforeach
</tr>
<tr>
<td>{{ $sum_total }}</td>
</tr>
#endforeach

Property does not exist on this collection instance. (Laravel 6)

I have a for-loop that adds <td> rows on my table. Problem is, I cannot access the attributes of my Schedule model and it keeps giving me
Property [date_of_shift] does not exist on this collection instance.
<table class="table table-bordered table-responsive">
<thead>
<th>Employee</th>
<!-- Format of date_of_shift field: format('Y-m-d') -->
#for ($i = 0; $i < 7; $i++)
<th>
{{ \Carbon\Carbon::today()->addDays($i)->format('F j, Y') }}<br />
{{ \Carbon\Carbon::today()->addDays($i)->format('D') }}
</th>
#endfor
</thead>
<tbody>
#foreach ($employees as $employee)
<tr>
<td>{{ $employee->user->last_name }}, {{ $employee->user->first_name }} {{ $employee->user->maiden_name }} </td>
#for ($j = 0; $j < 7; $j++)
#if ( $employee->schedule->date_of_shift == \Carbon\Carbon::today()->addDays($j)->format('Y-m-d') )
<td>{{ $employee->schedule->time_of_shift }}</td>
#else
<td><strong>REST DAY</strong></td>
#endif
#endfor
</tr>
#endforeach
</tbody>
</table>
Employee.php
public function schedule () {
return $this->hasMany('App\Schedule');
}
Schedule.php
public function employee () {
return $this->belongsTo('App\Employee');
}
What is a workaround for this?
Since your relationship is HasMany the $employee->schedule returns an instance of collection so in your case the easiest thing you can do is to get ->first() result of the collection...
#if ( $employee->schedule->first()->date_of_shift == \Carbon\Carbon::today()->addDays($j)->format('Y-m-d') )
<td>{{ $employee->schedule->first()->time_of_shift }}</td>
#else
<td><strong>REST DAY</strong></td>
#endif
OR
Or don't change any code in your blade instead change your relation from HasMany to HasOne
public function schedule () {
return $this->hasOne('App\Schedule');
}
Employee.php
public function schedules () {
return $this->hasMany('App\Schedule');
}
Schedule.php
public function employees () {
return $this->belongsTo('App\Employee');
}
And According to this employee can have many schedule so you cant do like
#if ( $employee->schedules->date_of_shift == \Carbon\Carbon::today()->addDays($j)->format('Y-m-d') )
<td>{{ $employee->schedules->time_of_shift }}</td>
#else
You have to use #foreach if u want to check many schedules
You can try this
#foreach($employee->schedules as $schedule)
#if ( $schedule->date_of_shift == \Carbon\Carbon::today()->addDays($j)
>format('Y-m-d') )
<td>{{ $schedule->time_of_shift }}</td>
#else
#endforeach
But if u want the latest one you can just utilize first() method like this
#if ( $employee->schedule->first()->date_of_shift == \Carbon\Carbon::today()->addDays($j)
>format('Y-m-d') )
<td>{{ $employee->schedule->first()->time_of_shift }}</td>
#else
But in case of schedule . It belongs to one employee so you dont have to use foreach
Thanks . Let me know if it helps

Laravel - Undefined property: Illuminate\Database\MySqlConnection::$username

I wrote a query to pass parameter from view to controller, and I got this error:
Undefined property: Illuminate\Database\MySqlConnection::$username
View Passing the parameter
<td width="25%"><a class="btn btn-info" href="{{ route('gamesListDetail',$game->id) }}">{{ $game->name }}</a></td>
Receiving Controller
public function gamesListDetail($id = null)
{
$gamelists = DB::table("platform_games")
->select("platform_games.id", "platform_games.username","game_player.game_id")
->join("game_player","game_player.game_id","=","platform_games.id")
->where('platform_games.id',$id)
->take(5);
return view('soccerrave.games.gamesListDetail', compact('gamelists'));
}
Receiving View
<tbody>
#foreach($gamelists as $key => $gamelist)
<tr>
<td>{{ ++$key }}</td>
<td>{{ $gamelist->username }}</td>
</tr>
#endforeach
<tr>
<td colspan="8">
{{ $gamelists->links() }}
</td>
</tr>
</tbody>
I expect the view to display top 5 data based on the parameter. But I got this error:
Undefined property: Illuminate\Database\MySqlConnection::$username
Documentation says:
skip / take
To limit the number of results returned from the query, or to skip a
given number of results in the query, you may use the skip and take
methods:
$users = DB::table('users')->skip(10)->take(5)->get();
So by example we see that after take method there must be get() call.
So fix Your code:
public function gamesListDetail($id = null)
{
$gamelists = DB::table("platform_games")
->select(
"platform_games.id",
"platform_games.username",
"game_player.game_id"
)
->join(
"game_player",
"game_player.game_id", "=", "platform_games.id"
)
->where('platform_games.id', $id)
->take(5)
->get(); // this one is required
return view('soccerrave.games.gamesListDetail', compact('gamelists'));
}

Trying to pass data from controller to view in laravel 5

I am trying to pass 2 different columns from my sql table to my view ,so that i can show them.
My controller is:
$interface = DB::table("users")->distinct()->get(['name']);
$interfac = DB::table("users")->distinct()->get(['email']);
view()->share('users',compact('interface','interfac'));
My view is :
#foreach ($users as $key => $value)
<tr>
<td>{{ $value->name }}</td>
<td>{{ $value->email }}</td>
</tr>
But this is not working while passing the two variables.If i pass one it is working but passing two is not working.thanks.
Controller
$users = DB::table('users')->get();
return view('users', compact('users'));

Resources