PHP-Laravel get data from pivot table in manytomany relation - php

I facing problem in fetching specific data from pivot table (manytomany relation). The scenario is that I want to fetch data from pivot table between two specific dates. When I use this code
$user_availability = $user->dates->where('date','>=' , $start_date)->where('date','<=' , $end_date)->get();
foreach ($user_availability as $date)
{
echo $date->pivot->afternoon;
}
It gives me following error
Type error: Too few arguments to function Illuminate\Support\Collection::get(), 0 passed in C:\xampp\htdocs\codehacking\app\Http\Controllers\UsersController.php on line 210 and at least 1 expected
User Model:
public function dates()
{
return $this->belongsToMany('App\Date')->withPivot('morning', 'afternoon','night','comment');
}
Pivot table
I can provide more information if you need. Any help would be appreciated.Thanks!

From Laravel documentation.
Querying Relations
Since all types of Eloquent relationships are defined via methods, you
may call those methods to obtain an instance of the relationship
without actually executing the relationship queries.
Relationship Methods Vs. Dynamic Properties
If you do not need to add additional constraints to an Eloquent
relationship query, you may access the relationship as if it were a
property.
Change the query to
$user_availability = $user->dates()->where('date','>=' , $start_date)->where('date','<=' , $end_date)->get();
parenthesis are used in the relation dates to querying the relation.

Related

I don’t know how to get data in laravel correctly by linking the data in this database

In this figure, the remaining tables are linked to the datainfo table. I need to retrieve the entire table data from the datainfo table.
In this picture I have shown the tables themselves
You can create Eloquent Models for each table and define Relationships among them. This is the Correct Laravel Way.
Let's assume Your datainfo table represents your Datainfo model,
Your cars table represents Car model. Same as washtypes and boxes.
then depending on your relation type defined the relation in Datainfo model.
class Datainfo extends Model
{
public function cars()
{
return $this->hasMany(Car::class);
}
}
You also can use hasOne instead of hasMany for one - to one relation
Similarly, create relation defining functions as washtypes() and boxes().
Then To get Datainfo with all related data using something like think in your controller
return Datainfo::with('cars','washtypes','boxes')->get();
Alternatively, you can get the count
return Datainfo::with('cars','washtypes','boxes')->count();
To get a count on a date
return Datainfo::with('cars','washtypes','boxes')->where('created_at',$date_var)->count();
If you only want Datainfo that has relation with cars, washtypes or boxes:
return Datainfo::has('cars','washtypes','boxes')->where('created_at',$date_var)->count();
Use laravel eloquent join clauses, https://laravel.com/docs/8.x/queries#joins
For total amount in same day
You can use eloquent sum and group by methods based on the date

Laravel Eloquent Model can't sync with pivot data in Many-to-Many relationship

I would like to sync the data instead of attach the data to the particular relationship.
Pivot relation UserModel code
public function carts(){
return $this->belongsToMany(Product::class,'user_carts')->withPivot('quantity');
}
The attach code is
User::find(1)->carts()->attach($s,["quantity"=>1]);
The sync code is
User::find(1)->carts()->sync($s,["quantity"=>1]);
When I try to compile the sync, those pivot relation that matched user_id = 1 does not have the "1" in its respective quantity column.
If I would like to achieve the sync function without using attach, how can I do it because the attach() will create multiple redundant data in my database.
You have to pass key values in the sync method.
Assuming $s is the id (key) to be synced:
User::find(1)->carts()->sync([$s => ["quantity"=>1]]);

Relationships: how to get 'one to one' data after many to many consult

as the title says I'm trying to access to a row that it's related to a one to one relationship, I've tried with the method that is in my model but it only works when the result isnt a collection, it maybe needs a more complicated consult, do you have any ideas how to do it with eloquent
Empresa model
public function transferencias_recibidas()
{
return $this->belongsToMany('App\Transferencia_recibir', 'empresa_transferencia_recibir', 'empresa_id', 'transferencia_recibir_id');
}
Transferencia_recibir model (the inverse of a hasOne relation)
public function transferencia()
{
return $this->belongsTo('App\Transferencia');
}
This is what i get, a collection
This is what a need for each one of them
$a=$empresa->transferencias_recibidas->find(1)->transferencia
Thx for the help guys
The eloquent relationship are "lazy loaded", meaning they will only load their relationship data when you actually access them. The output you shown are expected because you did not accessed that relationship, but you can load that relationship in two ways:
access it when needed:
$empresa->transferencias_recibidas->first()->transferencia;
"Eager load" all the transferencia relationship
Empresa::with('transferencias_recibidas.transferencia')->where([ .. ])->get();
The second method alleviates the N + 1 query problem. Since the first method executes N queries to retrieve all relationship, instead of a query to retrieve all the relationship for the second method.
You may need to check eager loading section.

How to get value from column that is in a N-N relationship table in Laravel

Im having a problem. I have two tables, places and cuisines, and cuisine_place and in that table I have a column called default (that shows if that cuisine is the default cuisine for that place). But Im having the problem that Im not able to access to that column.
How can I do?
What I want to do is have them in this answer:
$places = Place::all()->with('cuisines')->withPivot('default');
Something like that.
Thanks
You have a many to many relationship between places and cuisines. That relationship would be defined in the following fashion in your models:
public function cuisines(){
return $this->belongsToMany('Cuisine', 'cuisine_place');
}
The above would be a function in your Place class that references its relationship to the cuisines table. By default, Eloquent will pick up the foreign keys in the cuisine_place table (in your case they would probably be called cuisine_id and place_id). If you want to pick up additional columns from that table on calls to the above relationship function, you can use the withPivot function:
public function cuisines(){
return $this->belongsToMany('Cuisine', 'cuisine_place')->withPivot('default');
}
Now, on calls to the cuisines() method in your Place class, you'll receive the default column in the object associated with that table.
Open documentation for Laravel Eloquent Relationships
And read about Retrieving Intermediate Table Columns
You didn't provide your models code so it's difficult to help you with the exact solution

How should I structure the Eloquent ORM models for multiple intermediate tables in Laravel?

I can't find anywhere the information on how you have several intermediate tables with your Eloquent ORM models. The problem I'm facing is that I have a table for my users, permissions and roles. These are the 4 tables:
Permissions:
id
name
Permission_roles:
id
name
Permission_role_mappings:
id
permission_id
permission_role_id
Permission_role_user_mappings:
id
permission_role_id
user_id
(Well, I also have a users table but the layout of it doesn't matter since the foreign key is in permission_role_user_mapping.)
So the problem is that I want to be able to get the data from the permissions table when calling from the User model. I have some trouble grasping the workflow with Eloquent ORM altogether so if I'm missing something basic which is crucial then please point it out.
According to the documentation it seems that I don't need to create models for the intermediate tables. So how would I specify the relationship from the User class? Could I do something similar to this?
class User extends Eloquent {
public function permission_role()
{
return $this->has_many_and_belongs_to('Permission_Role', 'permission_role_user_mappings');
}
public function permission()
{
return $this->has_many_and_belongs_to('Permission_Role', 'permission_role_user_mappings')->has_many_and_belongs_to('Permission','permission_role_mappings');
}
}
This doesn't seem to be working, this is the error:
User::find(1)->first()->permission()->first();
...
Method [permission] is not defined on the Query class.
I also want to be able to get data by starting from Permission_Role and Permission. I'd prefer that the answer would help me specifying all the models required.
Eloquent relationships are accessed as an object property instead of a function.
User::find(1)->first()->permission;
You can wrap that above statement in the dd function to get a look at it.
This guide on Eloquent Relationships should be helpful
Edit for question in comments about selecting all permissions in the role:
$roles = array();
$permission_roles = User::find(1)->permission_roles()->get();
foreach ($permission_roles as $pr) {
if (! in_array($pr->permissions)) {
$roles[] = $pr->permissions;
}
}
This will get you what you want. However, this will end up doing a lot of queries. It's best to make use of Eager Loading here.

Categories