Laravel 5.1 specifing current page for pagination - php

Been working on this for far too long with no results. I have tried.
`\Illuminate\Pagination\Paginator::setCurrentPage($current_page);`
returns
Call to protected method Illuminate\Pagination\Paginator::setCurrentPage()
\Paginator::setCurrentPage($current_page);
returns Call to protected method Illuminate\Pagination\Paginator::setCurrentPage()
\DB::getPaginator()->setCurrentPage($current_page);
returns call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Database\MySqlConnection' does not have a method 'getPaginator'
$tmp = new Post( ); $tmp->getConnection()->setCurrentPage($current_page);
returns call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Database\MySqlConnection' does not have a method 'getPaginator'
How can I specify the page? I need to specify it manually.
I had hoped it to be as easy as $model->find( )->paginate($per_page, $page)

The Builder Class has:
public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
You can call
Model::find(...)->paginate($per_page, ['*'], 'page', $page);

Suppose you have $users to paginate in your UserController, you might do:
public function index()
{
$currentPage = 3; // You can set this to any page you want to paginate to
// Make sure that you call the static method currentPageResolver()
// before querying users
Paginator::currentPageResolver(function () use ($currentPage) {
return $currentPage;
});
$users = \App\User::paginate(5);
return view('user.index', compact('users'));
}
I believe this applies to Laravel 5.0 and above. Have to check on that.

for those people who using api and they want to specify the current page in api, they can use extra parameter like this:
getProducts?page=3

Related

Passing a variable to a ->each() function making the variable always = 0 php

One of the routes I'm making for my API in laravel requires me to pass a variable to a ->each() function.
This can be seen below:
public function by_location($zone_id)
{
$zone = Zone::where('id', $zone_id)->get()[0];
error_log($zone->id);
$exhibitors = Exhibitor::where('zone_id', $zone_id)->get();
$exhibitors->each(function($exhibitor, $zone)
{
error_log($zone->id);
$exhibitor['zone_info'] = $zone;
});
return response()->json($exhibitors);
}
This first error_log outputs '2', but with the second I get 'Trying to get property 'id' of non-object'.
Any help is apprecited!
You probably want to use $zone which you selected from database on first line.
Also if you want to change value of item you are iterating you have to use ->map() instead of ->each()
I changed ->get()[0] to ->first(). Never use ->get()[0]
public function by_location($zone_id)
{
$zone = Zone::where('id', $zone_id)->first();
error_log($zone->id);
$exhibitors = Exhibitor::where('zone_id', $zone_id)->get();
$exhibitors->map(function($exhibitor) use ($zone){
error_log($zone->id);
$exhibitor['zone_info'] = $zone;
return $exhibitor;
});
return response()->json($exhibitors);
}

Type error: Argument 2 passed to with() must be callable or null, object given

Route::get('/',function (){
$collection = collect(['product'=>'chair','price'=>100]);
//dd($collection);
return view('welcome')-with('prices',$collection);
});
I want to pass $collection on view but I get this error:
Type error: Argument 2 passed to with() must be callable or null,
object given
and I don't understand why.
Can somebody explain me?
Use ->with instead of -with:
return view('welcome')->with('prices',$collection);
Try this
$page_data = array(
'product'=>'chair',
'price'=>100
);
return \View::make('welcome', $page_data);
or
return view('welcome', $page_data);

Get URL parameters inside custom module

I've created a custom block like this:
class HelloBlock extends BlockBase implements BlockPluginInterface{
/**
* {#inheritdoc}
*/
public function build() {
$config = $this->getConfiguration();
$result = db_query('SELECT * FROM {test}');
return array(
'#theme' => 'world',
'#test' => $result
);
}
}
And I now want to programmatically get some parameter from the URL.
For example:
If the URL is http://localhost/drup/hello/5569 I want to get hold of the value 5569 inside my module.
I have tried arg(1) and drupal_get_query_parameters() but I got this error messages:
Call to undefined function `Drupal\hello\Plugin\Block\arg()`
and
Call to undefined function `Drupal\hello\Plugin\Block\drupal_get_query_parameters()`
How can I get the parameters?
Use \Drupal\Core\Routing;:
$parameters = \Drupal::routeMatch()->getParameters();
The named parameters are available as
$value = \Drupal::routeMatch()->getParameter('slug_name_from_route');
Where 'slug_name_from_router' comes from your routing.yml path property
path: '/your/path/{slug_name_from_route}'
If you want the raw parameter without any upcasting you can get
$value = \Drupal::routeMatch()->getRawParameter('slug_name_from_route');
I used to get the parameter value from URL (localhost/check/myform?mob=89886665)
$param = \Drupal::request()->query->all();
And applied in my select Query
$query = \Drupal::database()->select('profile_register', 'p1');
$query->fields('p1');
$query->condition('p1.mobileno', $edituseprof);
$query->condition('publishstatus', 'no');
$result = $query->execute()->fetchAll();
But on multiple parameter value, i am now successful(Ex: http://10.163.14.41/multisite/check/myform?mob=89886665&id=1)
$query = \Drupal::database()->select('profile_register', 'p1');
$query->fields('p1');
$query->condition('p1.mobileno', $edituseprof['mob']);
$query->condition('p1.ids', $edituseprof['id']);
$query->condition('publishstatus', 'no');
$result = $query->execute()->fetchAll();
arg() is deprecated in drupal 8, however we can get values like arg() function does in drupal 7 & 6
$path = \Drupal::request()->getpathInfo();
$arg = explode('/',$path);
print_r($arg); exit();
The output would be parameters in url except basepath or (baseurl),
Array
(
[0] =>
[1] => node
[2] => add
)
To get query parameter form the url, you can us the following.
If you have the url for example,
domainname.com/page?uid=123&num=452
To get "uid" from the url, use..
$uid = \Drupal::request()->query->get('uid');
To get "num" from the url, use..
$num = \Drupal::request()->query->get('num');
$route_match = \Drupal::service('current_route_match');
$abc = $route_match->getParameter('node'); //node is refrence to what you have written in you routing file i.e:
in something.routing.yml
entity.node.somepath:
path: '/some/{node}/path'
I have used {node} as arg(1). And I can access it by using *->getParameter('node');
Hope this will work.
If your url is like this below example
http://localhost/drupal/node/6666
Then you have to get the full url path by
$current_path = \Drupal::request()->getPathInfo();
then explode the path to get the arguments array.
$path_args = explode('/', $current_path);
Another example if value passed by a key in url like below where id contains the value
http://localhost/drupal?id=123
You can get the id by given drupal request
$id = \Drupal::request()->query->get('id');
Here's the example of accessing URL parameters and passing them to a TWIG template,
I am considering you have already created your module and required files and suppose "/test?fn=admin" is your URL
In Your .module file implement hook_theme and define variables and template name (Make sure you replace "_" with "-" when creating the template file)
function my_module_theme () {
return [
'your_template_name' => [
'variables' => [
'first_name' => NULL,
],
];
}
Now create your controller and put below code in it.
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;
class MyModule extends ControllerBase {
public function content(Request $request) {
return [
'#theme' => 'my_template',
'#first_name' => $request->query->get('fn'), //This is because the parameters are in $_GET, if you are accessing from $_POST then use "request" instead "query"
];
}
}
Now in your TWIG file which should be "my-template.html.twig" you can access this parameter as,
<h3>First Name: {{ first_name }}</h3>
And its done.
Hope this helps.
The Drupal docs are great on this: https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes
define your path variable in yaml
example.name:
path: '/example/{name}'
...
Add the variable in your method and use it
<?php
class ExampleController {
// ...
public function content($name) {
// Name is a string value.
// Do something with $name.
}
}
?>

Jump parameter in function

I have a controller in codeigniter called 'Main' with this function:
public function index ($id = false, $filter ='htmlentities') {
...
...
}
I want to call it through the URI 'jumping' the first parameter so that it remains 'false':
I would like to be able through the URI using something like:
'main/index/false/myfilter'
However this doesn't work, does anyone know how can I 'jump' this first parameter so that its value remains being false but i am able to change the filter?
(changing parameter order in function is NOT an option)
Just test for the string 'false' at the top of the controller method:
public function index ($id = false, $filter ='htmlentities') {
if ($id == 'false') {
$id = false;
}
// ...
}
Another possibility might be to use a custom route and simply discard the first parameter. In your app/config/routes.php file, add the rule:
$route['main/index/:filter'] = 'main/index/false/$1';
Now, when you visit 'main/index/myfilter', the $id parameter will be set to false (a string, not a boolean!)

CakePHP 1.3 paginate with custom query

I've managed to over-ride the default methods for a custom query in my model as suggested elsewhere,
function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array())
and
function paginateCount($conditions = null, $recursive = 0, $extra = array())
Unfortunately this approach over-rides all pagination for this model, and affects other pagination elsewhere. I found some code which may help where I could select whether I wanted the custom pagination used based on a variable e.g.
In my model
var $useCustom = false;
function paginateCount($conditions = null, $recursive = 0, $extra = array())
{
if(!$this->useCustom)
return parent::paginateCount($conditions, $recursive);
// code to handle custom paginate count here
}
I have found that using this method gives me an error,
Fatal error: Call to undefined method
AppModel::paginateCount() in....
What am I doing wrong? I assume that I would also need similar code in the paginate function as well? Am I also correct in thinking that I can set this variable in my controller i.e. $this->useCustom = 'true';
After a bit of delving into the code I found that the methods of paginateCount and paginate do not exist in the Model, or anywhere else for that matter, which is why I could not call them. The solution was copy the code from the main controller, which tests for the existence of the over-ride
For those that would like a similar solution use the following in paginateCount
if(!$this->useCustom)
{
$parameters = compact('conditions');
if ($recursive != $this->recursive) {
$parameters['recursive'] = $recursive;
}
$count = $this->find('count', array_merge($parameters, $extra));
return $count;
} else {
custom method...
}
and in paginate use
if(!$this->useCustom)
{
$parameters = compact('conditions', 'fields', 'order', 'limit', 'page');
if ($recursive != $this->recursive) {
$parameters['recursive'] = $recursive;
}
$results = $this->find('all', array_merge($parameters, $extra));
return $results;
} else {
custom method...
}
Hope this helps someone else.
I think you need the public keyword before your function to use the scope resolution operator in this way.
i.e. public function paginateCount(....

Categories