Laravel Eloquent Pagination orderBy first - laravel

I have a simple pagination from my model User:
$users = User::paginate(15);
Unfortunately, it returns the results ordered by id or something.
I want to order the results ASC first and then paginate on them.
Can't find any way to get that working in combination with the paginate() method, like:
$users = User::orderBy('username', 'asc')->paginate(15);
Any idea?
Thanks

I already test it like your code. It works. Can you give the error.
Route::get('/view-tags', function()
{
$tag = App\Tag::orderBy('name', 'asc')->paginate(5);
dd($tag);
});

Related

Laravel Spatie Call to undefined method Illuminate\Database\Query\Builder::assignRole()

Trying to do assignRole() to many users, but it show me Call to undefined method Illuminate\Database\Query\Builder::assignRole(). Is this spatie laravel bug?
$get_username = \App\Applicant::select('username')->whereIn('id', $ids);
$updateUser = \App\User::whereIn('username', $get_username);
$updateUser->assignRole('Applicant');
$updateUser->save();
Any solution for bulk assignRole() in this case?
$get_username = \App\Applicant::select('username')->whereIn('id', $ids);
This is an incomplete query via the QueryBuilder. As well as the second line.
When utilizing the QueryBuilder you need to finish of your queries with the get() method to get a collection to iterate over.
The correct execution would like like this:
$get_username = \App\Applicant::select('username')->whereIn('id', $ids)->get();
Without knowing the exact result of this, it looks like you'd like to retrieve a collection of usernames, that you'd like to get the User model from.
You could do something like the following (untested) for bulk updating.:
$users = User::whereIn('username', function($query) use ($ids) {
$query->select('username')
->from('applicants')->whereIn('id', $ids);
})->get();
foreach($users as $user) {
$user->assignRole('Applicant');
$user->save();
}

How to paginate and orderBy when getting data from relation model in laravel

I want to order by created_at posts in descending order
I also would like to paginate posts.
My issue is, I am not getting data directly through Post Model, I don't know how to do this.
I am using Laravel 5.7. This is what I have written inside a function in HomeController.
$id = auth()->user()->id;
$user = User::find($id);
return view('home')->with('posts',$user->posts);
Thank You.
Try this:
$posts = auth()->user()->posts()->latest()->paginate();
return view('home', compact('posts'));

Laravel Eloquent get result where relation data is null

I have two Models User and Owner with many to many relationship
I want to fetch only those users who don't have owner
how can I get using eloquent
i tried
$query = User::whereHas('userOwners', function ( $subquery ){
$subquery->whereNull('owner_id');
})->get();
but not working.
Eloquent has a way to query an absent relationships, it should work like this in your case:
$query = User::doesntHave('userOwners')->get();
User::with('userOwners')
->whereHas('userOwners', function ($query) {
$query->wherehas('owner_id');
})
->where('user_status', 1)->get();
use second where if you want to filter on user
use first where if you want to filter on Owner
I think you should just change your query like:
$query = User::whereHas('userOwners')->get();
Hope this work for you!!!

Laravel Eloquent: Get current id from inner function

I know, we can do this in the controller:
User::with('post')->get();
It will get every user's post from the database, based on users.id.
But the problem is, I want to do this:
User::with(['post' => function($query) {
# Throw users.id here...
}])->get();
How to do that?
You should get the users first, and then load related posts with a separate query and merge them manually.
$users = User::get();
$posts = Post::whereIn('user_id', $users->pluck('id'))->get(); // Get your additional data in this query
$users->each(function ($user) use ($posts)
{
$user->posts = $posts->where('user_id', $user->id);
});
Note: I did not test the code above. It's just an example to show you how to accomplish what you are trying to do.

Use Eloquent to attach array to query

I have a USER table, an ITEMS table, and a LIKES table. I'm randomly taking 9 items from the Items table (which is named 'categories') and I want to get an array of users which liked that item. I'm returning a JSON response so I can't use laravel's ORM relationships as far as I know. I want to be able to look through the results (with javascript) like so:
foreach item
item->price
....
foreach user
(this is how i wish to look through the users with js)
endforeach
endforeach
{{--Im trying to get an output that looks like so--}}
0: {
cost: 409
views: 0
...
user_like_id: {1,5,2,4,5}
}
EDIT: This is what I would like to attach the array to...
$likes = Category::orderByRaw("RAND()")
->leftJoin('likes', 'likes.item_id', '=', 'categories.id')
->take(9)
->get();
I'm relatively new to programming so please dont downnrate this question
Laravel provides in ways to make json from objects. The first and simplest is the eloquent toJson() method:
$likes = Category::orderByRaw("RAND()")
->leftJoin('likes', 'likes.item_id', '=', 'categories.id')
->take(9)
->get()
->toJson();
$likes is now json.
Second method:
If you return a model from a controller or a routecallback function, laravel returns it as json. So:
class MyController extends Controller{
public function getIndex(){
return Category::orderByRaw("RAND()")
->leftJoin('likes', 'likes.item_id', '=', 'categories.id')
->take(9)
->get();
}
}
This example returns a json response which is quite usefull!
I actually got exactly what I wanted with this:
$likes = Category::orderByRaw("RAND()")
->take(9)
->with(array('getLikes' => function($query)
{
$query->with('getUser');
}))
->get();
Works exactly how I want ito :) thanks for the suggestion tho

Resources