Laravel 5 Pagination Customisation - php

In Laravel 5, I am using simplePagination as outlined in the docs. I would like to customise the output so instead of double chevrons &rdaquo; '>>', I could put a right arrow. However I can't seen anywhere to customise it.
Does anyone know where the documentation for this is? Or where to begin looking?

While it is undocumented, it is certainly possible. It's pretty much the same as for Laravel 4. Basically all you need to is create a custom presenter and wrap the paginator instance.
Here's how a presenter might look like:
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Contracts\Pagination\Presenter;
use Illuminate\Pagination\BootstrapThreeNextPreviousButtonRendererTrait;
use Illuminate\Pagination\UrlWindow;
use Illuminate\Pagination\UrlWindowPresenterTrait;
class CustomPresenter implements Presenter
{
use BootstrapThreeNextPreviousButtonRendererTrait, UrlWindowPresenterTrait;
private $paginator;
private $window;
public function __construct(Paginator $paginator, UrlWindow $window = null)
{
$this->paginator = $paginator;
$this->window = is_null($window) ? UrlWindow::make($paginator) : $window->get();
}
public function render()
{
if ($this->hasPages()) {
return sprintf(
'<ul class="pagination">%s %s %s</ul>',
$this->getPreviousButton("Previous"),
$this->getLinks(),
$this->getNextButton("Next")
);
}
return null;
}
public function hasPages()
{
return $this->paginator->hasPages() && count($this->paginator->items() !== 0);
}
protected function getDisabledTextWrapper($text)
{
return '<li class="disabled"><span>'.$text.'</span></li>';
}
protected function getActivePageWrapper($text)
{
return '<li class="active"><span>'.$text.'</span></li>';
}
protected function getDots()
{
return $this->getDisabledTextWrapper("...");
}
protected function currentPage()
{
return $this->paginator->currentPage();
}
protected function lastPage()
{
return $this->paginator->lastPage();
}
protected function getAvailablePageWrapper($url, $page, $rel = null)
{
$rel = is_null($rel) ? '' : ' rel="'.$rel.'"';
return '<li><a href="'.htmlentities($url).'"'.$rel.'>'.$page.'</a></li>';
}
}
Then from your controller:
public function index()
{
$users = User::paginate(5);
$presenter = new CustomPresenter($users);
return view("home.index")->with(compact('users', 'presenter'));
}
The view:
#foreach ($users as $user)
<div>{{ $user->email }}</div>
#endforeach
{!! $presenter->render() !!}

Related

Codeigniter 4 Call to a member function get() on null

i have one project in CI3 and update for CI4
i have problem in my template, i receive Call to a member function get() on null.
my view not working call $this->traducao->get('search_string'); please help-me for update in class and libraries
My Function in Libraries
<?php
namespace App\Libraries;
use Config\Database;
class menus {
public $listMenus;
public $listSeo;
public function __construct(){
$this->set();
}
public function set(){
$db = Database::connect();
$builder = $db->table('menu');
$query = $builder->where("parente", 0)
->where("ativo", 1)
->orderBy('posicao', 'asc')
->get()->getResultArray();
if(is_array($query)){
$menusPai = $query;
}
$query2 = $builder->where("parente > 0")
->where("ativo", 1)
->orderBy('posicao', 'asc')
->get()->getResultArray();
if(is_array($query)){
$menusFilhos = $query2;
}
// $menusFilhos = ($query2->countAllResults() > 0) ? $query2->getResultArray() : false;
$menus = [];
foreach ($menusPai as $key => $value)
{
$this->listSeo[$value['link']]['pagina_titulo'] = $value['pagina_titulo'];
$this->listSeo[$value['link']]['pagina_keywords'] = $value['pagina_keywords'];
$this->listSeo[$value['link']]['pagina_description'] = $value['pagina_description'];
$menus[$value['id']]['filhos'] = [];
$menus[$value['id']]['dados'] = $value;
if ($menusFilhos)
{
foreach ($menusFilhos as $k => $v)
{
if ($v['parente'] == $value['id'])
{
$this->listSeo[$v['link']]['pagina_titulo'] = $v['pagina_titulo'];
$this->listSeo[$v['link']]['pagina_keywords'] = $v['pagina_keywords'];
$this->listSeo[$v['link']]['pagina_description'] = $v['pagina_description'];
$menus[$value['id']]['filhos'][] = $v;
}
}
}
}
$this->listMenus = $menus;
}
public function get(){
return $this->listMenus;
}
public function seo($tag){
$uri = new \CodeIgniter\HTTP\URI();
print_r($uri);
$uri = ($this->CI->uri->uri_string() == '') ? '/' : $this->CI->uri->uri_string();
return $this->listSeo[$uri][$tag];
// return $this->listSeo[$uri][$tag];
}
}
My ControllerBase
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Libraries\My_parser;
use App\Libraries\Preferencia;
use App\Models\index_model;
use App\Libraries\Traducao;
use App\Libraries\Menus;
class BaseController extends Controller
{
protected $helpers = [];
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
$this->_db = \Config\Database::connect();
$this->My_parser = new My_Parser();
$this->_model = new \App\Models\index_model();
$this->traducao = new Traducao();
}
public function output($data, $status){
$this->output
->set_status_header(200)
->set_content_type('application/json', 'utf-8')
->set_output(
json_encode(
array(
'status'=> $status,
'response'=> $data
),
JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
)
)->_display();
exit;
}
}
And my view
<div class="container">
<h2 class="text-center no-m"><?= $this->traducao->get('HOME_EMPRESAS_PARCEIRAS_TITULO') ?></h2>
and my index.php loading views layout
<?= $this->extend('template/head.php',array('css'=> $css, 'metatags'=> $metatags)) ?>
<?= $this->extend('template/header.php') ?>
<?= $this->extend('template/navbar.php') ?>
<?= $this->section('content')?>
<?= $this->endSection()?>
The short answer is it doesn't exist in the View because you never gave it to the View.
$this->traducao belongs to the Controller. It may have been constructed with the Controller but there's no immediate reason that any View would have access to it (or any data that wasn't passed directly to the View).
All incoming requests should be routed through Controllers; that is their most important purpose. Where is the Controller that's actually handling the request to your index.php file?
Any and all Views should be displayed by a Controller because that is where you have the ability to pass data (i.e. $this->traducao) into the View.
If this is actually CI4 as tagged, then you have a problem with CI3 code still being present as well; for example, $this->output isn't used to return Controller responses in CI4, it's $this->response instead.

How to return one instance of a eloquent many to many relation with eager loading?

class Parent extends Model
{
public function kids()
{
return $this->belongsToMany('App\Models\Kid')
->orderBy('age')
->withTimestamps();
}
public function oldestKid()
{
return $this->belongsToMany('App\Models\Kid')
->orderByDesc('age')
->take(1);
}
}
Problem with this approach is that $parent->oldestKid returns an array. It would feel more logical if it would return an object.
$parent = App\Models\Parent::with('oldestKid')->first();
This is what we ended up with, and its working.
Important to add: the pivot table is kid_parent
public function oldestKid()
{
return $this->belongsTo(Kid::class, 'oldest_kid_id', 'id');
}
public function scopeWithOldestKid($query)
{
$query->addSelect(['oldest_kid_id' => KidParent::select('kid_id')
->whereColumn('parent_id', 'parents.id')
->join('kids', 'kids.id', '=', 'kid_parent.kid_id')
->orderByDesc('kids.age')
->take(1)
])->with('oldestKid');
}
then you can use it like that :
$parents = Parent::withOldestKid()->get();
foreach($parents as $parent){
$oldest_kid = $parent->oldestKid;
}
If you want to go crazy: you can use https://laravel.com/docs/8.x/eloquent#global-scopes so it is always loaded in if you go for a parent.
You have to use a subquery to do that :
public function oldestKid()
{
return $this->belongsTo(Kid::class);
}
public function scopeWithOldestKid($query)
{
$query->addSelect(['oldest_kid_id' => Kid::select('id')
->whereColumn('parent_id', 'parents.id')
-> orderByDesc('age')
->take(1)
])->with('oldestKid');
}
then you can use it like that :
$parents = Parent::withOldestKid()->get();
foreach($parents as $parent){
$oldest_kid = $parent->oldestKid;
}

App\PageList::coupon must return a relationship instance in laravel 5.5

I am trying to get a count() from database but I am getting an error.
I am trying to find how many N are in is_ordered field.
My Model look like:
public function coupon()
{
return $this->hasOne('App\PageCoupon','page_id','business_id')
->where('is_ordered','N')->count();
}
and my blade view:
<p>{{optional($value->coupon)->is_ordered}}</p>
I am unable to find a solution.
your help will be highly appreciated!
public function pageListHere()
{
$list = PageList::all();
return view('page-list',compact('list'));
}
class PageList extends Model
{
protected $table = 'page_master';
protected $fillable = ['business_id', 'page_url', 'page_name'];
public function particulars()
{
return $this->hasOne('App\Sale','user_id','business_id');
}
public function coupon()
{
return $this->hasOne('App\PageCoupon','page_id','business_id');
}
}
You can try doing it this way.
Leave your first function coupon like this:
public function coupon()
{
return $this->hasOne('App\PageCoupon','page_id','business_id')->where('is_ordered','N');
}
And then you can have a second function as so:
public function couponCount()
{
return $this->coupon->count();
}
After that you can use it in blade on your variable like so: $coupon->couponCount();
Your code and what you want is little bit confusing. try this:
PageList.php
public function coupon()
{
return $this->hasMany('App\PageCoupon','page_id','business_id');
}
Controller
public function pageListHere()
{
$list = PageList::all();
return view('page-list',['list'=>$list]);
}
View
#foreach($list as $listItem)
<p>{{$listItem->coupon()->where('is_ordered','N')->count()}}</p>
#endforeach

Pass setting data from database to layout

I want to pass data from de setting table from the database to my layout view.
How do I get it done?
$item = Setting::find(1);
return view($this->controller.'/show')->with( 'item', $item);
Solution:
public function boot() {
if( !isset( $_SESSION['adminTitle'] ) ){
$item = Setting::find(1);
$item = $item->toArray();
$_SESSION['adminTitle'] = $item['title'];
$_SESSION['adminEmail'] = $item['email'];
$_SESSION['adminLogo'] = $item['logo'];
}
}
Why not simply this?:
// File app/Http/Controllers/ExampleController.php
//
class ExampleController extends Controller
{
public function show()
{
//
$setting = Setting::find(1);
return view('example', ['setting' => $setting]);
}
}
Within the Blade view:
<!-- resources/views/example.blade.php -->
{{ $setting->title }}
{{ $setting->logo }}
...
But, if you want to share settings between all your views, you can add this middleware:
// File app/Http/Middleware/ViewShareSettingMiddleware
//
class ViewShareSettingMiddleware
{
public function handle($request, Closure $next)
{
$setting = Setting::find(1);
view()->share('setting', $setting);
return $next($request);
}
}
Create your view in:
\resources\views\
Example: \resources\views\index.blade.php
$data['item'] = Setting::find(1);
return view('index')
->with( $data);
Or
$item = Setting::find(1);
return view('index', compact('item');
View: {{$item}}

laravel hook into Eloquent pre and post save for every model

I'm new to Laravel and ORM's in general. How could i hook into Eloquent to fire code before and after a save of any model? I know i can do the following for specific models but i'm looking at figuring out how to do this for every model.
class Page extends Eloquent {
public function save()
{
// before save code
parent::save();
// after save code
}
}
Using laravel models own life cycle events may solve this easy
/**
* model life cycle event listeners
*/
public static function boot(){
parent::boot();
static::creating(function ($instance){
//
});
static::created(function ($instance){
//
});
}
There's even a better way of accomplishing this! Create an observer for, lets say a model called House:
class HouseObserver {
public function saving(House $house) {
// Code before save
}
public function saved(House $house) {
// Code after save
}
}
Now register the observer with the House model by adding the line House::observe(new HouseObserver) somewhere. The line can be added in the boot method of the model:
class House extends Eloquent {
// Lots of model code
public static function boot() {
parent::boot();
self::observe(new HouseObserver);
}
}
More info can be found here.
You can create a BaseModel class that extends eloquent and then have all your models extend BaseModel. Here's an example:
abstract class Elegant extends Eloquent{
/* Save ****************************/
public function preNew() {}
public function postNew() {}
public function preSave() { return true; }
public function postSave() {}
public function save($validate=true, $preSave=null, $postSave=null)
{
$newRecord = !$this->exists;
if ($validate)
if (!$this->valid()) return false;
if($newRecord)
$this->preNew();
$before = is_null($preSave) ? $this->preSave() : $preSave($this);
// check before & valid, then pass to parent
$success = ($before) ? parent::save() : false;
if ($success)
is_null($postSave) ? $this->postSave() : $postSave($this);
if($newRecord)
$this->postNew();
return $success;
}
public function onForceSave(){}
public function forceSave($validate=true, $rules=array(), $messages=array(), $onForceSave=null)
{
if ($validate)
$this->valid($rules, $messages);
$before = is_null($onForceSave) ? $this->onForceSave() : $onForceSave($this); // execute onForceSave
return $before ? parent::save() : false; // save regardless of the result of validation
}
/** Soft Delete ****************************/
public function preSoftDelete() { return true; }
public function postSoftDelete() { }
public function softDelete($val = true, $preSoftDelete=null, $postSoftDelete=null)
{
if ($this->exists)
{
$before = is_null($preSoftDelete) ? $this->preSoftDelete() : $preSoftDelete($this);
$success = null;
if($before) {
$this->set_attribute(static::$softDelete, $val);
$success = $this->save(false);
}
else
$success = false;
if ($success)
{
is_null($postSoftDelete) ? $this->postSoftDelete() : $postSoftDelete($this);
}
return $success;
}
}
/** Hard Delete ****************************/
public function preDelete() { return true;}
public function postDelete(){}
public function delete( $preDelete=null, $postDelete=null)
{
if ($this->exists)
{
$before = is_null($preDelete) ? $this->preDelete() : $preDelete($this);
$success = ($before) ? parent::delete() : false;
if ($success)
{
is_null($postDelete) ? $this->postDelete() : $postDelete($this);
}
return $success;
}
}
}

Categories