Laravel - pagination with created_at pages sorting - laravel

So guys I'm working on this project and I need laravel pagination. I already tried laravel basic pagination with $posts->links() on my blade but it is not working. I think like there is some update on it or something. I need pagination to be paginate by created_at, so on one page it needs to show me all posts created at same day. Can you pls help me
Here is my HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Post;
use DB;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('home')->with('posts', $user->posts);
}
}
Here is my home.blade.php
#extends('layouts.theme')
#section('content')
<style>
body{
margin: 0;
background-color: #EBEBEB;
}
</style>
<div class="mainl">
<div class="row">
<div class="columna">
<h1>{{ Auth::user()->name }}</h1>
<hr>
</div>
<div class="columns">
<a href="{{ route('logout') }}" id="logout"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
{{ __('LOGOUT') }}
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
#csrf
</form>
</div>
</div>
</br></br></br>
#if(count($posts)> 0)
<table>
<thead>
<tr>
<th>BR.KESICE</th>
<th>IME I PREZIME</th>
<th>BR.TELEFONA</th>
<th>POSAO</th>
<th>CIJENA</th>
<th>PLACANJE</th>
<th>POPUST</th>
<th>DATUM PREUZ.</th>
<th>DATUM IZDAV.</th>
<th>SMJENA</th>
<th>RADNIK</th>
<th>STATUS</th>
<th>IZMIJENI</th>
</tr>
</thead>
<tbody>
#foreach($posts as $post)
<tr>
<td>{{$post->br_kesice}}</td>
<td>{{$post->ime}}</td>
<td>{{$post->br_telefona}}</td>
<td>{{$post->posao}}</td>
<td>{{$post->cijena}}</td>
<td>{{$post->placanje}}</td>
<td>{{$post->popust}}</td>
<td>{{$post->datum_preuz}}</td>
#if($post->status == 1)
<td>/</td>
#else
<td>{{$post->datum_izdav}}</td>
#endif
<td>{{$post->smjena}}</td>
<td>{{$post->radnik}}</td>
<td>
#if($post->status == 0)
<span class="label label-primary" id="statusdeaktivan">Deaktivan</span>
#elseif($post->status == 1)
<span class="label label-success" id="statusaktivan">Aktivan</span>
#elseif($post->status == 2)
<span class="label label-danger" id="statusdeaktivan">Rejected</span>
#else
<span class="label label-info" id="statusdeaktivan">Deaktivan</span>
#endif
</td>
#if($post->status == 3)
#else
<td><i class="far fa-edit"></i></td>
#endif
</tr>
#endforeach
</tbody>
<tfoot>
<tr>
<th>UKUPAN IZNOS: {{ Auth::user()->posts->sum('cijena')}}€</th>
<th>KARTICA: {{ Auth::user()->posts->where('placanje', 'Kartica')->sum('cijena')}}€</th>
<th>GOTOVINA: {{ Auth::user()->posts->where('placanje', 'Gotovina')->sum('cijena')}}€</th>
<th>VIRMAN: {{ Auth::user()->posts->where('placanje', 'Virman')->sum('cijena')}}€</th>
</tr>
</tfoot>
</table>
#else
<p>Trenutno nema unosa.</p>
#endif
</div>
#endsection
if you need anything else to help, please comment and I will add it.

It is because you're not getting your posts paginated, but all of them.
You just need to change $user->posts to $user->posts()->paginate() for it to work. Optionally, you may pass a number to the paginate method to tell it how many records per page do you need.
Hope it helps!

Related

Laravel Pagination To Certain Section

Guys
I'm using Laravel's default pagination with bootstrap as its styling framework.
I want to direct my page to certain html section after I click the pagination link, so far I only know how to paginate like the following codes:
Controller:
$data = Products::paginate(9);
return view('index', ['data' => $data]);
Blade:
{{ $data->links() }}
So, I want to direct my page to a certain section in html everytime I clicked the pagination link button. how can I achieve that?
I'm sorry for my poor explanation, hit me up if you need more detail.
Thank You
you should make a blade file like this:
pagination.blade.php
#if ($paginator->hasPages())
<ul class="pagination justify-content-center">
#if ($paginator->onFirstPage())
<li class="paginate_button page-item previous disabled">
قبلی
</li>
#else
<li class="paginate_button page-item previous">
pre
</li>
#endif
#foreach ($elements as $element)
#if (is_string($element))
<li class="paginate_button page-item active">
<a href="javascript:void(0)" class="page-link" >{{ $element }}</a>
</li>
#endif
#if (is_array($element))
#foreach ($element as $page => $url)
#if ($page == $paginator->currentPage())
<li class="paginate_button page-item active">{{ $page }}</li>
#else
<li class="paginate_button page-item ">{{ $page }}</li>
#endif
#endforeach
#endif
#endforeach
{{-- next page --}}
#if ($paginator->hasMorePages())
<li class="paginate_button page-item next ">
next
</li>
#else
<li class="paginate_button page-item next disabled">
بعدی
</li>
#endif
</ul>
#endif
then create a blade file like this:
table.blade.php
#if(isset($permissions))
#php
$paginator=$permissions;
#endphp
<table class="table table-striped">
<thead>
<tr>
heaers tags
</tr>
</thead>
<tbody id="table-data">
#foreach ($permissions as $permission)
tr tags
#endforeach
</tbody>
</table>
#endif
<div class="col-md-12">
{{ $paginator->links('sections.pagination') }}
</div>
then in controller method:
public function index(Request $request)
{
$permissions=Permission::paginate(5);
if($request->ajax()){
return view('sections.table',compact('permissions'));
}
return view('permission.index',compact('permissions'));
}

Sorting and searching a foreign entity field on a Laravel Livewire table

I’ve just implemented a Livewire data table based on the Caleb’s tutorial on Laracasts. Everything works as expected when working with just one model. However I’m stuck trying to apply sorting and searching to a foreign model field.
User model:
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use Notifiable;
use HasRoles;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Get the user's email verified status.
*
* #param string $value
* #return string
*/
public function getEmailVerifiedAtAttribute($value)
{
if ($value == null) {
return "No";
}
return $value;
}
public function getRoleAttribute()
{
if($this->roles()->count() > 0) {
return $this->roles()->first()->name;
} else {
return "Usuario registrado";
}
}
public static function search($query)
{
return empty($query) ? static::query()
: static::where('name', 'like', '%'.$query.'%')
->orWhere('email', 'like', '%'.$query.'%');
}
}
Tried adding another orWhere() clause to the search() method in some ways. None worked. Now I left just the default ones.
Livewire controller:
namespace App\Http\Livewire\Users;
use Livewire\Component;
use Livewire\WithPagination;
class Table extends Component
{
use WithPagination;
public $perPage;
public $sortField;
public $sortAsc;
public $search;
public function mount()
{
$this->perPage = 10;
$this->sortField = 'name';
$this->sortAsc = true;
$this->search = '';
}
public function sortBy($field)
{
if ($this->sortField === $field) {
$this->sortAsc = ! $this->sortAsc;
} else {
$this->sortAsc = true;
}
$this->sortField = $field;
}
public function updatingPerPage()
{
$this->resetPage();
}
public function render()
{
return view('livewire.users.table', [
'users' => \App\User::search($this->search)
->with('roles')
->orderBy($this->sortField, $this->sortAsc ? 'asc' : 'desc')
->paginate($this->perPage),
]);
}
}
Livewire view:
<div>
<div class="row mb-4">
<div class="col form-inline">
Mostrar
<select wire:model="perPage" class="form-control form-control-sm custom-select custom-select-sm">
<option>10</option>
<option>100</option>
<option>1000</option>
</select>
registros
</div>
<div class="col-sm-3">
<input wire:model="search" class="form-control form-control-sm" type="text" placeholder="Buscar usuarios...">
</div>
</div>
<div class="table-responsive mb-4" >
<div class="table-header">
<table class="table table-sm text-nowrap" role="grid">
<thead>
<tr>
<th width="30%">
<a wire:click.prevent="sortBy('name')" role="button" href="#">
Nombre
#include('partials._sort-icon', ['field' => 'name'])
</a>
</th>
<th width="30%">
<a wire:click.prevent="sortBy('email')" role="button" href="#">
Correo electrónico
#include('partials._sort-icon', ['field' => 'email'])
</a>
</th>
<th width="30%">
<a wire:click.prevent="sortBy('')" role="button" href="#">
Rol
#include('partials._sort-icon', ['field' => ''])
</a>
</th>
<th></th>
</tr>
</thead>
</table>
</div>
<div class="table-body">
<table class="table table-sm table-hover text-nowrap" role="grid">
<tbody>
#foreach ($users as $user)
<tr>
<td width="30%">{{ $user->name }}</td>
<td width="30%">{{ $user->email }}</td>
<td width="30%">{{ $user->role }}</td>
<td>
<form method="POST" action="{!! route('backend.users.user.destroy', $user->id) !!}" accept-charset="UTF-8">
<input name="_method" value="DELETE" type="hidden">
{{ csrf_field() }}
<div class="btn-group btn-group-xs float-right" role="group">
#can('users.show')
<a href="{{ route('backend.users.user.show', $user->id ) }}" class="btn btn-outline-default btn-xs" title="{{ trans('users.show') }}">
<i class=" fas fa-fw fa-eye" aria-hidden="true"></i>
</a>
#endcan
#can('users.edit')
<a href="{{ route('backend.users.user.edit', $user->id ) }}" class="btn btn-outline-default btn-xs" title="{{ trans('users.edit') }}">
<i class=" fas fa-fw fa-pencil-alt" aria-hidden="true"></i>
</a>
#endcan
#can('users.destroy')
<button type="submit" class="btn btn-outline-default btn-xs" title="{{ trans('users.delete') }}" onclick="return confirm("{{ trans('users.confirm_delete') }}")">
<i class=" fas fa-fw fa-trash-alt" aria-hidden="true"></i>
</button>
#endcan
</div>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
<div class="table-footer">
<div class="text-muted">
Showing {{ $users->firstItem() }} to {{ $users->lastItem() }} out of {{ $users->total() }} results
</div>
<div>
{{ $users->links() }}
</div>
</div>
</div>
Tried also some ways to pass an argument to the sortBy() and [‘field’ => ‘’] on the role column. Now I left them with empty strings.
I know, this issue probably is more related to Laravel than Livewire, but I’ll really appreciate any help.
Update:
Solved using the Laravel Query Builder instead of Eloquent.

Display data in a treeviewDisplay data in a treeview

I'm Working on Laravel.
I'm trying to display my data in a treeview. But i success only the first step. Someone of you can help please ?
DataBase Structure
My achievement
Code:
<button class=" btn-primary" type="button" data-toggle="collapse" data-target=".multi-collapse" aria-expanded="false" aria-controls=".multi-collapse" >
<span class="glyphicon glyphicon-eye-open"></span></button>
#foreach(App\Account::where('nomencloture', 'LIKE', '_')->get() as $item)
<div class="collapse multi-collapse" id="{{$item->nomencloture}}" >
<div class="list-group-item " >
<div class="col-md-2"> {{ $item->account_id }}</div>
<div class="col-md-2"> {{ $item->account_name }}</div>
<button class=" btn-primary" type="button" data-toggle="collapse" data-target="#PUT SOMETHINGHERE" aria-expanded="false" aria-controls="multiCollapseExample1" >
<span class="glyphicon glyphicon-eye-open"></span></button>
<br>
<br>
#foreach(App\Account::where('nomencloture', 'LIKE', '_______')->get() as $subitem)
<div class="collapse" id="{{ $subitem->nomencloture }}" >
<br>
<div class="list-group-item ">
<div class="col-md-2"> {{ $subitem->account_id }}</div>
<div class="col-md-2"> {{ $subitem->account_name }}</div>
</div>
</div>
#endforeach
</div>
</div>
#endforeach
You need to make some changes in your code, please find below step to change code
Step 1: Please create relations with your foreign key in your model file like
namespace App;
use Illuminate\Database\Eloquent\Model;
class Treeview extends Model
{
protected $table = 'treeview';
public $fillable = ['title','parent_id'];
/**
* Get the index name for the model.
*
* #return string
*/
public function childs() {
return $this->hasMany('App\Treeview','parent_id','id') ;
}
}
Step 2: Add below function in your controller and make some changes according to your table and model object
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function manageCategory()
{
$categories = Treeview::where('parent_id', '=', 0)->get();
return view('treeview/categoryTreeview',compact('categories')); // set the path of you templates file.
}
Step 3 : Add below code in your categoryTreeview templates file
<h3>Category List</h3>
<ul id="tree1">
#foreach($categories as $category)
<li>
{{ $category->title }}
#if(count($category->childs))
#include('treeview/manageChild',['childs' => $category->childs]) // Please create another templates file
#endif
</li>
#endforeach
</ul>
Step 4: Please Create another templates file manageChild add below code.
<ul>
#foreach($childs as $child)
<li>
{{ $child->title }}
#if(count($child->childs))
#include('treeview/manageChild',['childs' => $child->childs])
#endif
</li>
#endforeach
</ul>
Output displayed Like:
Category List
Cat_1
Cat_1_par_1
Cat_1_par_2
Cat_1_par_3
Cat_2
Cat_2_par_1
Cat_2_par_2
Cat_2_par_3
Cat_3
More information I found one link: https://itsolutionstuff.com/post/laravel-5-category-treeview-hierarchical-structure-example-with-demoexample.html

Import data into database and show it on html table in laravel

I want to create a view in laravel that has a function to import an excel file into the database and show it in a table inside a view.
I created a controller and it imports the excel data in database but fails to show it in view.
Please Help solve my issue.
Many Thanks in advance.
Best Regards,
Dian
I am using laravel 5.5 and maatwebsite excel
public function importFileIntoDB(Request $request){
if($request->hasFile('sample_file')){
$path = $request->file('sample_file')->getRealPath();
$data = Excel::load($path, function($reader) {})->get();
if($data->count()){
foreach ($data as $key => $value) {
$arr[] = ['name' => $value->name, 'details' => $value->details];
}
if(!empty($arr)){
\DB::table('products')->insert($arr);
dd('Insert Record successfully.');
}
}
}
return back()->with($arr);
}
this is my view
#extends('frontpage')
#section('title', 'Dashboard')
#section('content_header')
<h1>Upload File From Excel Into Database</h1>
#stop
#section('content')
<div class="panel panel-primary">
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title" style="padding:12px 0px;font-size:25px;"><strong>Test - import export csv or excel file into database example</strong></h3>
</div>
<div class="panel-body">
#if ($message = Session::get('success'))
<div class="alert alert-success" role="alert">
{{ Session::get('success') }}
</div>
#endif
#if ($message = Session::get('error'))
<div class="alert alert-danger" role="alert">
{{ Session::get('error') }}
</div>
#endif
<h3>Import File Form:</h3>
<form style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 20px;" action="{{ URL::to('importExcel') }}" class="form-horizontal" method="post" enctype="multipart/form-data">
<input type="file" name="import_file" />
{{ csrf_field() }}
<br/>
<button class="btn btn-primary">Import CSV or Excel File</button>
</form>
<br/>
<h3>Import File From Database:</h3>
<div style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 20px;">
<button class="btn btn-success btn-lg">Download Excel xls</button>
<button class="btn btn-success btn-lg">Download Excel xlsx</button>
<button class="btn btn-success btn-lg">Download CSV</button>
</div>
<h3>Table Import List </h3>
<div style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 20px;" >
print_r($arr->count());
#if(!empty($arr))
<table class="table table-striped table-hover table-reflow">
#foreach($arr as $key=>$value)
<tr>
<th ><strong> {{ $key }}: </strong></th>
<td> {{ $value }} <td>
</tr>
#endforeach
</table>
#endif
</div>
</div>
</div>
</div>
#stop
#section('css')
<link rel="stylesheet" href="/css/admin_custom.css">
#stop
#section('js')
<script> console.log('Hi! this is frontpage'); </script>
#stop
As conveyed by #gbalduzzi you need to return the data to the view as
return back()->with(['arr' => $arr]);
and access in your view as
#if(session()->has('arr'))
<table class="table table-striped table-hover table-reflow">
#php $arr = session('arr'); #endphp
#foreach($arr as $key => $value)
<tr>
<th ><strong> {{ $value['name'] }}: </strong></th>
<td>{{ $value['details'] }} <td>
</tr>
#endforeach
</table>
#endif
Docs
Change
return back()->with($arr);
with
return back()->with(['arr' => $arr]);
return back()->with('arr', $arr); // Should be equivalent
return back()->compact($arr); // Should be equivalent
The with method doesn't accept only a single value: you need to specify an array, a key and a value or use the compact method

Accessing collection from a relationship

So I have 2 tables.
DirtyEvent model and Event model.
I am retrieving DirtyEvent with Event which works fine
In blade I have:
#if (\Request::is('profile/event'))
#foreach ($events as $event)
#if (empty( $event->image ))
<div class="card-header">
<span class="card-title"> {{($event->title) }}</span>
</div>
#else
<div class="card-image">
<img class="img-responsive" src="{{ $event->image }}"></img>
<span class="card-title"> {{($event->title) }}</span>
</div>
#endif
<div class="card-content">
<p><strong>Starts: </strong>#php echo ($startdate) #endphp - {{$event->startime }}</p>
<br>
#if ($startdate != $enddate)
<p><strong>Ends: </strong>#php echo ($enddate) #endphp - {{$event->endtime }}</p>
<br>
#endif
<p><strong>Description:</strong></p>
<br>
<p>{{$event->description }}</p>
</div>
<div class="card-action">
<i class="fa fa-pencil-square-o fa-2x" aria-hidden="true"></i>
<form method="POST" action={{ url('events/delete/' . $event->id) }}>
{{ method_field('PATCH') }}
{{ csrf_field() }}
<button type="submit" class="delete" style="border:none;"><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></button>
</form>
</div>
#foreach ($events->publicevents as $eventss)
{{dd($events)}}
#endforeach
#endforeach
However dd($events) gives me:
DirtyEvent Collection -> relations -> publicevents -> Event collection
But, It is saying that publicevents do not exist in current collection.
Controller
public function index()
{
$id = Auth::id();
$events = DirtyEvent::where('user_id', $id)
->with('publicevents')
->get();
return view('events.viewEvent', compact('events'));
}
Model
public function publicevents()
{
return $this->hasMany('App\Event', 'event_id');
}
I guess not all dirty event objects have events. So check this first with empty() or isEmpty() or count():
#if (!empty($event->publicevents))
#foreach ($event->publicevents as $eventss)
{{ $eventss->id }}
#endforeach
#endif
Update
It should be $event->publicevents, not $events->publicevetns.

Resources