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.
Related
I am new to laravel and trying to have a result.
My code is this:
class GegonosController extends Controller
{
public function index($gid = null, $cid = null, $nid = null)
{
if (is_null($cid) and is_null($nid) and is_null($gid)) {
$gegon = Gegono::orderBy('created_at','desc')->get();
}
else{
if(!is_null($gid)) {
if($gid == 0) {
$gegon = Gegono::where('gegtype_id','>',1);
}
else{
$gegon = Gegono::where('gegtype_id', '=', $gid);
}
}
else {
$gegon = Gegono::where('gegtype_id','>',0);
}
if (!is_null($cid)) {
$gegon->where('city_id', '=',$cid);
}
if (!is_null($nid)) {
$gegon->where('nomos_id','=', $nid);
}
$gegon->orderBy('created_at','desc')->get();
}
$nomoi = \App\Nomoi::orderby('name')->get();
return view('front.gegonota', compact('gegon','gid','cid','nid','nomoi'));
}
In the first, if when all variables are null the result is a collection of all the records of the table.
In all other, if (other cases) the result is a builder and I get no results,
It doesn't show any error but gives no results.
Any help would save me a lot of time.
Query Builder's get() method returns the collection of records. In your code, you just call get() method in the air, so it does nothing. You should assign it to a variable or use it in an expression.
Source: https://laravel.com/docs/5.4/eloquent#collections
I would like to use attach() on a filtered Builder result:
$users = User::whereIn('type', array(1, 2))->get();
$usersType_1 = $users->filter(function($item) {
return $item->type == 1;
});
$usersType_2 = $users->filter(function($item) {
return $item->type == 2;
});
$usersType_1->role()->attach(3);
$usersType_2->role()->attach(4);
So, I need to attach the role based on the user type. The role() method is specified on the User model
The attach() part from the code above throws the following error: Method role() doesn't exist - which I assume happens because filter() returns a Collection.
Is there a working way to attach pivot entries on filtered Builder result? Or do I need to run 2 separate queries and run attach() on them respectively?
You couldn't use role method no collection instead of User model. Try by:
$users = User::whereIn('type', array(1, 2))->get();
$usersType_1 = $users->filter(function($item) {
if($item->type == 1) {
return $item->role()->attach(3);
}
})
->all();
$usersType_2 = $users->filter(function($item) {
if($item->type == 2) {
return $item->role()->attach(4);
}
})
->all();
Alternative :
$users = User::whereIn('type', array(1, 2))->get();
$usersType_1 = $users->filter(function($item) {
$item->type == 1;
})
->all();
$usersType_2 = $users->filter(function($item) {
return $item->type == 2;
})
->all();
$role1 = Role::find(3);
$role2 = Role::find(4);
$role1->users()->attach($usersType_1->puck('id'));
$role2->users()->attach($usersType_2->puck('id'));
Why not just do:
$usersType_1 = $users->where('type', 1); // or whereType(1)
$usersType_1->role()->attach(3);
$usersType_2 = $users->where('type', 2); // or whereType(1)
$usersType_2->role()->attach(4);
I think the "Method role() doesn't exist" exception occurs because you're filtering an Eloquent Collection.
EDIT: I see why this doesn't work. It's because you're trying to attach an entire collection to a role. It would work if you used find() and then attached a role.
So you should loop over all the users with type 1 and attach the role
foreach ($usersType_1 as $user) {
$user->role()->attach(3);
}
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'm builind a form with laravel to search users, this form has multiple fields like
Age (which is mandatory)
Hobbies (optional)
What the user likes (optional)
And some others to come
For the age, the user can select in the list (18+, 18-23,23-30, 30+ etc...) and my problem is that i would like to know how i can do to combine these fields into one single query that i return to the view.
For now, i have something like this :
if(Input::get('like')){
$users = User::where('gender', $user->interested_by)->has('interestedBy', Input::get('like'))->get();
if(strlen(Input::get('age')) == 3){
$input = substr(Input::get('age'),0, -1);
if(Input::get('age') == '18+' || Input::get('age') == '30+' )
{
foreach ($users as $user)
{
if($user->age($user->id) >= $input){
$result[] = $user;
// On enregistre les users étant supérieur au if plus haut
}
else
$result = [];
}
return view('search.result', ['users' => $result]);
}
elseif (strlen(Input::get('age')) == 5) {
$min = substr(Input::get('age'), 0, -3);
$max = substr(Input::get('age'), -2);
$result = array();
foreach($users as $user)
{
if($user->age($user->id) >= $min && $user->age($user->id) <= $max)
$result[] = $user;
}
return view('search.result', ['users' => $result]);
}
}
else
$users = User::all();
And so the problem is that there is gonna be 2 or 3 more optional fields coming and i would like to query for each input if empty but i don't know how to do it, i kept the age at the end because it's mandatory but i don't know if it's the good thing to do.
Actually this code works for now, but if i had an other field i don't know how i can do to query for each input, i know that i have to remove the get in my where and do it at the end but i wanna add the get for the last query..
Edit: my models :
User.php
public function interestedBy()
{
return $this->belongsToMany('App\InterestedBy');
}
And the same in InterestedBy.php
class InterestedBy extends Model{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'interested_by';
public function users()
{
return $this->belongsToMany('App\User');
}
}
you can use query builer to do this as follow
$userBuilder = User::where(DB::raw('1')); //this will return builder object to continue with the optional things
// if User model object injected using ioc container $user->newQuery() will return blank builder object
$hobbies = Request::input('hobbies') // for laravel 5
if( !empty($hobbies) )
{
$userBuilder = $userBuilder->whereIn('hobbies',$hobbies) //$hobbies is array
}
//other fields so on
$users = $userBuilder->get();
//filter by age
$age = Request::input('age');
$finalRows = $users->filter(function($q) use($age){
return $q->age >= $age; //$q will be object of User
});
//$finalRows will hold the final collection which will have only ages test passed in the filter
A way you could possible do this is using query scopes (more about that here) and then check if the optional fields have inputs.
Here is an example
Inside your User Model
//Just a few simple examples to get the hang of it.
public function scopeSearchAge($query, $age)
{
return $query->where('age', '=', $age);
});
}
public function scopeSearchHobby($query, $hobby)
{
return $query->hobby()->where('hobby', '=', $hobby);
});
}
Inside your Controller
public function search()
{
$queryBuilder = User::query();
if (Input::has('age'))
{
$queryBuilder ->searchAge(Input::get('age'));
}
if (Input::has('hobby'))
{
$queryBuilder->searchHobby(Input::get('hobby'));
}
$users= $queryBuilder->get();
}
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);
}