Laravel pagination problem with User::find($user_id) - php

I got this piece of code in Laravel:
public function index()
{
$user_id = auth()->user()->id; // gets the current user id
$user = User::find($user_id); // find the specific user id
$validPosts = $user->posts->paginate(5)->whereIn('status', ['Pending', 'Processing']);
return view('home', compact('validPosts'));
}
I want to return all posts that have the status pending and processing with pagination that has the value of 5 but I am getting the following error:
Method Illuminate\Database\Eloquent\Collection::paginate does not
exist.
I know that I have failed somewhere at $user->posts->paginate(5).
What should I do?

Paginate method works with Eloquent models. Retrieve the model, apply whereIn first and then paginate it. Try this:
public function index() {
$user = auth()->user();
$validPosts = $user->posts()->whereIn('status', ['Pending', 'Processing'])->paginate(5);
return view('home', $validPosts);
}
Now in your "home" view file you can use $validPosts

You can try this way
public function index()
{
$user_id = auth()->user()->id; // gets the current user id
$user = User::find($user_id); // find the specific user id
// paginate function should be last
$validPosts = $user->posts()->whereIn('status', ['Pending', 'Processing'])->paginate(5);
// if you want to pass more variable, do it like this
return view('home', ['validPosts' => $validPosts]);
}
or you can do it like this
public function index()
{
$user_id = auth()->user()->id; // gets the current user id
// paginate function should be last
$validPosts = Post::where('user_id', $user_id)->whereIn('status', ['Pending', 'Processing'])->paginate(5);
// if you want to pass more variable, do it like this
return view('home', ['validPosts' => $validPosts]);
}
Hope this help you.

Related

How to get query of users in Laravel with where condition

I have a table for users and in that table, I have the column user_type_id which is related to another table called user_types. There are specific roles(subscriber and admin). Now, In my controller, I want to get all users with the condition that their user_type_id is equal to 2. With this way of doing it, I am getting only the first row...
My Controller:
public function show($id)
{
$subscriber = User::where('user_type_id', 2)->firstOrFail();
return view('show_subscriber', compact('subscriber'));
}
public function show($id) {
$subscriber = User::where('user_type_id', 2)->get();
return view('show_subscriber', compact('subscriber'));
}
public function show($id) {
$subscriber = User::where('user_type_id', 2)->firstOrFail();
return view('show_subscriber', compact('subscriber'));
}
firstOrFail() will return the first matching record and if no matching record is found it will simply return 404- resource not found.
public function show($id) {
$subscriber = User::where('user_type_id', 2)->get();
return view('show_subscriber', compact('subscriber'));
}
get() will return all the matching records as a collection.
see details here https://laravel.com/docs/9.x/eloquent#not-found-exceptions.
https://laravel.com/docs/9.x/eloquent#collections

How do you display list of admin with is_admin attribute in laravel?

How do you display all list of admin that have column with the is_admin=1? with this query? because we are not passing any data in showListAdmin.
public function Admin()
{
$users = User::all();
return view('admin.admins')->with('users',$users);
}
simply use where ....
public function showListAdmin()
{
$users = User::where('is_admin',true)->get()->all();
return view('admin.admins')->with('users',$users);
}

Having difficulties displaying all content on my wishlist table

I am trying to retrieve the data on my wishlist table, for a particular user, so far it only retrieves the first data on the table, just returning one array instead of the three in the table with same user id
public function getWishlistByUserId($id){
$wishlists = Wishlist::where('userId', $id)->get();
foreach($wishlists as $wishlist){
$products = Product::where('id', $wishlist->productId)->get();
return $products;
}
}
It happens because the foreach loop returns a value during the first iteration. Place your return statement outside the loop. Also you could improve your performence by making use of relationships.
An example could be:
// Product.php
public function wishlists()
{
return $this->hasMany(Wishlist::class);
}
// Your method
public function getWishlistByUserId($id)
{
return Product::whereHas('wishlists', function ($query) use ($id) {
$query->where('userId', $id);
});
}
Ideally this is n+1 situation
So i will suggest to use laravel relationship like:
in your whishlist model
public function product(){
return $this->hasMany(Product::class,'productId','id');
}
get data with relationship
public function getWishlistByUserId($id){
$wishlists = Wishlist::with('product')->where('userId', $id)->get();
}
I was finally able to get it working this way, i just pushed the result into an array, and then returned it outside the loop, thanks everyone for your help
public function getWishlistByUserId($id){
$wishlists = Wishlist::where('userId', $id)->get();
$wishlist = [];
foreach($wishlists as $wish){
$product = Product::where('id', $wish->productId)->get();
array_push($wishlist, $product);
}
return $wishlist;
}

laravel dynamic scope not working

I try to get my categories base on their status and i have scope below in my category model:
public function scopeOfStatus($query, $status)
{
return $query->where('status_id', $status);
}
And my controller is like:
public function finder() {
$findercategories = Category::OfStatus('Active')->get();
return response()->json($findercategories);
}
My route is like:
Route::get('/finder','frontend\SearchController#finder');
But i get blank page as result. Any idea?
update
if i use $findercategories = Category::ofStatus(1)->get(); i get the result that i want but it's static not dynamic :\
Get the Id's from the statuses table with respect to the searched value and use the Id's to get the Category
public function scopeOfStatus($query, $status)
{
$statuses = Status::where('title', $status)->pluck('id'); // Or relevant column name
return $query->whereIn('status_id', $statuses);
}
and in your Controller you could do so
public function finder() {
$findercategories = Category::ofStatus('Active')->get();
return response()->json($findercategories);
}

Laravel 5.1: Call to undefined method Illuminate\Database\Query\Builder::fill()

I am trying to get this line to work $user->profile()->fill($input['profile'])->save();
Following much discussion and failed attempts
I need help filling an eloquent model
Also had a probelm with guarding
http://laravel.io/forum/01-06-2016-massassignmentexception-ignoring-fillable-guarded-is-set
Which i overcame with protected $guarded = ['id'];
Profile model
public function user(){
return $this->belongsTo('App\User');
}
User Model
public function profile(){
return $this->hasOne('App\Profile', 'user_id');
}
Controller
public function update(Request $request, $id)
{
$user = User::with('profile')->findOrFail($id);
$input = $request->all();
if(is_null($user->profile)){
$profile = new Profile($input['profile']);
$user->profile()->save($profile);
alert()->warning('New profile creation attempt!');
}else{
// $user->profile()->fill($input['profile'])->save();
$user->profile->title = $input['profile']['title'];
$user->profile->facebook_username = $input['profile']['facebook_username'];
$user->profile->meetup_user_id = $input['profile']['meetup_user_id'];
$user->profile->save();
// dump($input['profile']['title']);
// dump($user->profile->title);
//Unless it fails silently like before.
alert()->success('Profile Saved!');
}
return redirect()->route('admin.users.edit', [$id]);
}
Notice how I am manually filling, this is not ideal obviously. this is the result i am trying to achieve
as per my understanding, you want to fill profile Attributes in a single line,
did you try fill() method ??
try this way in your else section or whereever your want it, I hope that might help you
$profile = new Profile;
$profile->fill($input['profile']);
$user->profile()->save($profile);

Categories