Being new to this framework faced a problem that the resultset is not paginated with the use of standart ->paginate() method if I want to get the result with relations. What is the best approach to achieve the desired ?
Here is my method :
public function findAll($perPage = 15, $order = 'ASC', $orderBy = 'id')
{
$users = User::orderBy($orderBy, $order)->with('permissions','companies')->paginate($perPage);
$users = $users->toArray();
return $users['data'];
}
There's actually no need to convert the result object into array, so in your example you can actually do something like this in the function:
$users = User::orderBy($orderBy, $order)->with('permissions','companies')->paginate($perPage);
return $users;
Then to access the values in your view:
foreach ($users as $user){
echo $user->name;
}
Related
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;
}
I have array of collections. In collections I have relation. How I can use whereIn in these relations?
$arrayCollections = $category->products;
$arrayCollections = $arrayCollections->character->whereIn('id', [1,2,3,4]); //I need use whereIn in character relation. I get error: Property [character] does not exist on this collection instance.
foreach($arrayCollections as $product) {
.... //but in foreach I can use $product->character
}
Relation in product model::
public function character()
{
return $this->hasMany('App\Models\ProductCharacter');
}
Try this:
$characters = $category->products()->character()->whereIn('id', [1,2,3,4])->get();
foreach($characters as $character) {
// $character
}
You seem to need an indirect relationship. The best way to get this is by using hasManyThrough
In your Category model
public function characters() {
return $this->hasManyThrough(Character::class, Product::class); // Has many characters through products
}
Then you can directly do:
$characters = $category->characters()->whereIn('id', [ 1, 2, 3, 4 ])->get();
what about this ? I added first() :
$characters = $category->products()->first()->character()->whereIn('id', [1,2,3,4])->get();
foreach($characters as $character) {
// $character
}
You can try this
$arrayCollections = $category->products()->with('character')->whereIn('id' , [1,2,3,4])->get();
foreach($arrayCollections as $product) {}
You should use the whereHas() methode and with() method.
$arrayCollections = $category->products()
->whereHas('character', function($character){
$character->whereIn('id' , [1,2,3,4]);
})
->with('character')->get();
This will get you a collection of "products" that have "characters" attach to it that have ID in [1,2,3,4].
I want to display all my users with relations. Currently I have:
FilterController.php
public function getFilter($sport)
{
$user = Auth::user();
$users = $this->model->getUsersByDiscipline($sport);
return view('filter.' . $sport, compact('user', 'users'));
}
User.php
public function getUsersByDiscipline($sport)
{
$users = User::with('user_data', 'languages')->where('discipline', $sport)->get();
return $users;
}
And I try to display it like:
{{$user->user_data->employment}}
But there's error:
Property [employment] does not exist on this collection instance
How to do it correctly?
If employment is a relationship, I think it's not loaded yet. So you may load using nested eager loading.
In your eloquent query, you can use this:
$users = User::with('user_data.employment', 'languages')->where('discipline', $sport)->get();
Notice the dot syntax meaning employment is a relationship of user_data, it will now be loaded and accessible through: $user->user_data->employment
Reference: https://laravel.com/docs/5.5/eloquent-relationships#nested-eager-loading
$users = User::with('user_data', 'languages')->where('discipline', $sport)->get();
by doing this you will get the array of $users
so you need to run a loop
#foreach($users as $user)
{{ $user->user_data()->employment }}
#endforeach
Or you can debug a code in control
$users = User::with('user_data', 'languages')->where('discipline', $sport)->get();
foreach($users as $user){
dd($user->user_data()); //check what it returns in user_data;
}
I want to get REST url to retrieve data where name="hello" and category="main"
This is my Model
public function show($name, $category)
{
$FodMap = FodMap::find($name, $category);
return $FodMap;
}
Routes
Route::get('FodMap/{name}/{category}', 'FodMapController#show');
What I want is when I type localhost/api/FodMap/hello/main
All result should display which matches with hello and main
Please advise me to proceed.... I'm new to Laravel.
The eloquent query is something like this:
FodMap::where('name','=',$name)->where('category','=',$category)->get()
That will return an Eloquent Collection instance.
public function getAllData()
{
$data = tableName::where('Method','Delivery')->get();
return response()->json($data, 200);
}
OR
$users = DB::table_Name('users')->select('name', 'email as user_email')->get();
OR
$users = DB::table('users')
->whereIn('id', [1, 2, 3])
->get();
I am playing with Laravel models and I need one to return a value that is not in the db table but it comes by running a model method. This method runs a query that groups and count grouped results.
The model method works just fine but I don't seem to be able to pre-fill the $quantity variable within the constructor with something different than 0.
So this is an excerpt of the model:
public $quantity;
function __construct($attributes = array(), $exists = false) {
parent::__construct($attributes, $exists);
$this->quantity = $this->quantity();
}
public function quantity()
{
$query = DB::table('carts_shopping')
->select('cart_id', DB::raw('COUNT(*) AS quantity'))
->where('cart_id',$this->cart_id)
->groupBy('cart_id')
->first();
return ($query) ? $query->quantity : 0;
}
While this is how I am trying to retrieve the results from controller:
$cartitems = Auth::user()->cartshopping;
foreach ($cartitems as $cartitem)
{
echo $cartitem->name;
echo $cartitem->quantity;
}
As you may guess 'cartshopping' comes from the user model being related with the model excerpt I pasted.
I also noticed that quantity() method gets called and it returns 0 all the time as if $this->cart_id was empty and, changing $this-cart_id with a real value the query itself doesn't even get executed.
Thanks a lot for any suggestion you guys can share.
Have you tried accessing the properties using $this->attributes?
public $quantity;
function __construct($attributes = array(), $exists = false) {
parent::__construct($attributes, $exists);
$this->quantity = $this->quantity();
}
public function quantity() {
$query = DB::table('carts_shopping')
->select('cart_id', DB::raw('COUNT(*) AS quantity'))
->where('cart_id', $this->attributes['cart_id'])
->groupBy('cart_id')
->first();
return ($query) ? $query->quantity : 0;
}
Failing that, you could try using the Eloquent accessors, which would be the best way to do it. This would make it dynamic as well, which could be useful.
class YourModel {
// Normal model data here
public function getQuantityAttribute() {
$query = DB::table('carts_shopping')
->select('cart_id', DB::raw('COUNT(*) AS quantity'))
->where('cart_id', $this->attributes['cart_id'])
->groupBy('cart_id')
->first();
return ($query) ? $query->quantity : 0;
}
}