I'm trying to extract some code to a private function inside a controller in order to tidy it up a bit, but the function seems not to run.
Route:
Route::resource('posts', 'PostsController');
When I GET the following URL:
/posts?page=2&posts_per_page=3&published=0
It ignores the page and posts_per_page variables (i.e. it just returns the first 10 unpublished results) But when I had this code inside the index
method it worked.
public function index()
{
// set defaults for page number and posts per page
$page = 1;
$postsPerPage = 10;
$published = 1;
$this->getPagesAndPostsPerPage($page, $postsPerPage);
// Get published or not
// Not published = 0
// Published = 1
if ( Input::has('published') )
{
$published = Input::get('published');
}
// return paginated results
$skip = ($page - 1) * $postsPerPage;
$posts = Post::where('published', '=', $published)
->orderBy('published_date', 'desc')
->skip($skip)
->take($postsPerPage)
->get();
return Response::json([
'data' => $this->transformCollection($posts)
], 200);
}
// Get pages and posts per page
private function getPagesAndPostsPerPage($page, $postsPerPage)
{
// if posts per page and page are defined
if ( Input::has('posts_per_page') && Input::has('page') )
{
// get inputs
$postsPerPage = Input::get('posts_per_page');
$page = Input::get('page');
}
// else if just page is defined
elseif ( Input::has('page') )
{
$page = Input::get('page');
}
}
Can anyone see what I'm doing wrong?
You're not returning anything from $this->getPagesAndPostsPerPage($page, $postsPerPage);
Variables defined inside a function are function specific, which means you need to pass function variables back and forth if you need to grab their updated value. Either that, or use class variables (properties) so you can access the updated value from anywhere in your code.
Your controller:
public function index()
{
// set defaults for page number and posts per page
$page = 1;
$postsPerPage = 10;
$published = 1;
// Get the return value:
$pagesAndPostsPerPage = $this->getPagesAndPostsPerPage($page, $postsPerPage);
Your getPagesandPostsPerPage()
function:
private function getPagesAndPostsPerPage($page, $postsPerPage){
//Grab pages and posts per page here
//Create a new array and set the values
$pagesAndPostsPerPage = array(
'page' =>$page,
'postsPerPage'=>$postsPerPage,
);
//Return the array
return $pagesAndPostsPerPage;
}
If you need more explanation let me know! I'd be glad to help you out further.
EDIT:
Forgot to mention, you can also pass the variable as a reference to the function if you don't want to provide a return value to functions using the ampersand (&
) operator to just modify them.
http://php.net/manual/en/language.references.pass.php
Example:
function addOne(&$number)
{
$number++;
// Notice no return statement
}
$number = 1;
addOne($number);
echo $number; // Returns 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With