i have this code:
public function test(){
$results = Cand::paginate(4);
if (Request::ajax()) {
return Response::json(View::make('admin.posts')->with('results', $results)->render());
}
$this->layout->content = View::make('admin.dashboard')->with('results', $results);
}
It works fine, but when a user enters a page that does not exist in the URL, like "?page=9999", how can I restrict this?
You can get the last page by calling getLastPage() on your paginator instance:
if ( Input::get('page', 1) > $results->getLastPage() )
{
App::abort(404);
}
Related
I use octobercms and User Extended plugin(Clacke). I try to render a pagination because for now i have a lot of registered users and they display on one page.
I use random users function from \classes\UserManager.php
public static function getRandomUserSet($limit = 7)
{
$returner = new Collection;
$userCount = User::all()->count();
if(!isset($userCount) || empty($userCount) || $userCount == 0)
return [];
if($userCount < $limit)
$limit = $userCount;
$users = User::all(); //paginate(5)
if(empty($users))
return $returner;
$users->random($limit);
$friends = FriendsManager::getAllFriends();
foreach($users as $user)
{
$userAdd = true;
if(!$friends->isEmpty())
{
foreach($friends as $friend)
{
if($user->id == $friend->id)
{
$userAdd = false;
break;
}
}
}
if($user->id == UserUtil::getLoggedInUser()->id)
$userAdd = false;
if($userAdd)
{
$returner->push($user);
}
}
return $returner->shuffle();
}
try to do this with changing return $returner->paginate(25); and $users = User::paginate(25); but throws me an error
An exception has been thrown during the rendering of a template
("Method paginate does not exist.").
After that i try to change directly in \components\User.php
public function randomUsers()
{
return UserManager::getRandomUserSet($this->property('maxItems'))->paginate(12);
}
But again the same error.
Tryed and with this code and render in default.htm {{ tests.render|raw }}
public function randomUsers()
{
$test = UserManager::getRandomUserSet($this->property('maxItems'));
return $test->paginate(10);
}
Again with no success. Could anyoune give me some navigation and help to fix this?
If you are using random users function from \classes\UserManager.php
I checked the code and found that its using Illuminate\Support\Collection Object. So, for that Collection Object pagination works differently
You need to use forPage method.
On the other hands paginate is method of Illuminate\Database\Eloquent\Collection <- so both collection are not same
Use forpage
// OLD return UserManager::getRandomUserSet($this->property('maxItems'))
// ->paginate(12);
TO
return UserManager::getRandomUserSet($this->property('maxItems'))
->forPage(1, 12);
forPage method works like forPage(<<PAGE_NO>>, <<NO_OF_ITEM_PER_PAGE>>);
so if you use forPage it will work fine.
if any doubt please comment.
I have a function in my helper
function somethingOrOther($id)
{
$posts = Posts::where('author_id', $id);
$posts_count = [];
$posts_count['total'] = $posts->count();
$posts_count['published'] = $posts->where('status', 'published')->count();
$posts_count['draft'] = $posts->where('status', 'draft')->count();
return $posts_count;
}
and this function works perfectly fine. But now I'm trying use it in this function in a controller to return it to a view
public function profile($id)
{
$posts_count[]= somethingOrOther($id);
return view ('display.profile')->withPosts_count($posts_count['total'])->withPosts_published_count($posts_count['published'])->withPosts_draft_count($posts_count['draft']);
}
But I get an error of 'Undefined index: total'. What do I need to do to separately return the array values of $posts_count?
I belive you can just do
$posts_count= somethingOrOther($id);
and then return it like
return view ('display.profile',["posts_count" => $posts_count]);
and in blade get it like
{{$posts_count["total"]}}
Try with
$post_count = $this->somethingOrOther($id);
if ( !$post_count ) {
return "no posts for this author";
}
...
return view('display.profile', compact('post_count'));
In view
{{ $post_count['total'] }}
I get comments paginated. And I need to check, if I have the id of a comment, then open the page that comment is in. Here is my code:
public function show_comments(Request $request) {
$cmnt_id = $request->input('cmnt_id');
if ( isset( $cmnt_id ) ){
// I need to get all comments paginated but start from the page that $cmnt_id is in it
} else {
// starts from page 1
$comments = Cmnt_tb::paginate(10);
}
return View('show_cmnts', compact('comments'));
}
How can I do that? any idea?
I think I have to make a new URL and redirect to it.
Maybe there is a better solution, but I guess something like this will work for you:
public function show_comments(Request $request) {
$cmnt_id = $request->input('cmnt_id');
$perPage = 10;
if (isset($cmnt_id)){
// Get row number.
$rowNumber = Cmnt_tb::where('id', '<=', $cmnt_id)->count();
// Get page.
$page = ceil($rowNumber / $perPage);
return redirect('show-comments-url?page='.$page);
} else {
$comments = Cmnt_tb::paginate($perPage);
return view('show_cmnts', compact('comments'));
}
}
I have a resource:
Route::resource('artists', 'ArtistsController');
For a particular url (domain.com/artists/{$id} or domain.com/artists/{$url_tag}), I can look at the individual page for a resource in the table artists. It is controlled by this function:
public function show($id)
{
if(!is_numeric($id)) {
$results = DB::select('select * from artists where url_tag = ?', array($id));
if(isset($results[0]->id) && !empty($results[0]->id)) {
$id = $results[0]->id;
}
}
else {
$artist = Artist::find($id);
}
$artist = Artist::find($id);
return View::make('artists.show', compact('artist'))
->with('fans', Fan::all())
->with('friendlikes', Fanartist::friend_likes())
->with('fan_likes', Fanartist::fan_likes());
}
What I would like to do is have all urls that are visited where the {$id} or the {$url_tag} don't exist int he table, to be rerouted to another page. For instance, if I typed domain.com/artists/jujubeee, and jujubee doesn't exist in the table in the $url_tag column, I want it rerouted to another page.
Any ideas on how to do this?
Thank you.
In your show method you may use something like this:
public function show($id)
{
$artist = Artist::find($id);
if($artist) {
return View::make('artists.show', compact('artist'))->with(...)
}
else {
return View::make('errors.notfound')->withID($id);
}
}
In your views folder create a folder named errors (if not present) and in this folder create a view named notfound.blade.php and in this view file you'll get the $id so you may show something useful with/without the id.
Alternatively, you may register a global NotFoundHttpException exception handler in your app/start/global.php file like this:
App::error(function(Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e) {
// Use $e->getMessage() to get the message from the object
return View::make('errors.notfound')->with('exception', $e);
});
To redirect to another page have a look at the redirect methods available on the responses page of the Laravel docs.
This is how I would go about doing it and note that you can also simplify your database queries using Eloquent:
public function show($id)
{
if( ! is_numeric($id)) {
// Select only the first result.
$artist = Arist::where('url_tag', $id)->first();
}
else {
// Select by primary key
$artist = Artist::find($id);
}
// If no artist was found
if( ! $artist) {
// Redirect to a different page.
return Redirect::to('path/to/user/not/found');
}
return View::make('artists.show', compact('artist'))
->with('fans', Fan::all())
->with('friendlikes', Fanartist::friend_likes())
->with('fan_likes', Fanartist::fan_likes());
}
I created a helper for returning a user's username if the user's unique id is known.
if ( ! function_exists('get_username'))
{
function get_username($user_id)
{
$ci=& get_instance();
$ci->load->database();
if (empty($user_id))
{
return FALSE;
}
$ci->db->select('username');
$ci->db->where('id', $user_id);
$ci->db->where('activated', 1);
$ci->db->where('banned', 0);
$ci->db->limit(1);
$query = $ci->db->get('users');
if ($query->num_rows() > 0) //if user exists
{
$row = $query->row();
return $row->username;
}
else
{
return FALSE;
}
}
}
This works in my view if for instance I try:
echo get_username($this->uri->segment(3)); //uri segment 3 is a user id.
However want to send the username to my view via controller. I tried the following in my controller:
function write_message($user_id = '') //function parameter is 3rd uri segment
{
$data['username'] = get_username($user_id);
$this->load->view('my_view', $data);
}
Then in my view I have
echo $username which echoes array instead of the username. What am I doing wrong here?
Your criteria should be clear, and the usrname should be unique i think, so...
if ($query->num_rows() == 1) //if user exists, and unique
{
$res = $query->result_array();
return $res[0]['username'];
}
else
{
return FALSE;
}
Upon using <pre>print_r($username)</pre> in my view (as suggested by Alfonso) it was easy to spot the issue, being an identical variable name in my view which was another array. Correct answer goes to anyone that gives a good suggestion/input for my helper or Alfonso if he submits his post as answer.