Method addEagerConstraints does not exist - laravel

I have two models, User and Event. I made a pivot table, invitations between User and Event with a status column. In my Event model definition, I wrote this :
public function invited()
{
return $this->belongsToMany(User::class, 'invitations', 'event_id', 'user_id')
->withTimestamps()
->withPivot('status')
->orderByDesc('invitations.updated_at');
}
public function participants()
{
$event = $this->with([
'invited' => function ($query) {
$query->where('invitations.status', InvitationStatus::ACCEPTED)->get();
}
])->first();
return $event->invited;
}
But when in my controller I do :
$event = Event::where('id', $id)->with(['owner', 'participants'])->first();
I have the following error :
(1/1) BadMethodCallException
Method addEagerConstraints does not exist.
Does someone know why?

When you're trying to do this:
->with('participants')
Laravel expects to get a relationship instance. In other words, you can't use this method as a relation.

where should come before with. This is what eloquent expects.
It should be like this:
$event = Event::with(['owner', 'participants'])->where('id', $id)->first();

Related

Sort inside the with in laravel

$posts = PostUrl::with(['post' => function ($q) {
$q->orderBy('created_at', 'DESC');
}])
->where('category','like' ,'%'.$cat.'%')
->paginate(8);
How can I sort the result as per the created_at of the post inside?
When try to ->orderBy('post.created_at','DESC') it show column not found.
Add PostUrl models
public function post(){
return $this->hasMany('App\Post', 'postid')->orderBy('created_at', 'DESC');
}
Controller :
$posts = PostUrl::with(['post'])->where('category','like' ,'%'.$cat.'%')->paginate(8);
Make sure you have established correctly in your PostUrl model the relationship with your Post model (if it is so called). You should have a function similar to the following in your model in order to with() method works correctly in the controller:
public function post(){
return $this->hasMany('App\Post', 'postid');
}
This way there should be no problem for the orderBy clause to work properly.

Laravel one to one (polymorphic) not working only on specific model

I am facing a super weird issue.
I have 3 tables and their equivalent model:
App\User
public function company() {
return $this->morphTo();
}
App\Supplier
public function user() {
return $this->morphOne(User::class, 'company');
}
App\Company
public function users() {
return $this->morphMany(User::class, 'company');
}
For some reason the relationship on App\Supplier does not work, but all the other works normal, I can even get the supplier if I have the user:
$supplier = \App\Supplier::find(1);
$company = \App\Company::find(2);
$supplieruser = \App\User::find(1);
$supplier->user //THIS RETURN NULL
$company->users //return collection of users normally
$suppplieruser->company //returns an instance of supplier model
I have tried, changing the name of the relationship and nothing.
Any idea?
In case someone find this in the future... the relationship was not working because I had in my AppServiceProvider the following:
Relation::morphMap([
.....
'supplier_to_supplier' => 'App\Supplier',
.....
]);
It seems that registering it here will affect all the morphs from that model.

Laravel Polymorphic Relationships with order by

Laravel version 7.2.5.
I am using Polymorphic Relationships to store the access logs (login, logout) for multi-role application.
The data storing part is working completely fine. Now, I need to show the list of records in desc format with pagination. But, It's loading the data in the asc format
SomeModel.php
class SomeModel extends Model
{
/**
* Polymorphic Relationships
*/
public function loginLog()
{
return $this->morphMany(LoginLog::class, 'employable');
}
public function show($token)
{
return self::where([
'token' => $token,
])->with([
'loginLog:employable_id,ip,created_at,updated_at'
])->first() ?? null;
}
}
I did find the solution. But, somehow it doesn't feel the appropriate way to solve this issue.
Here is the link Laravel order results by column on polymorphic table
Try this
class SomeModel extends Model
{
/**
* Polymorphic Relationships
*/
public function loginLog()
{
return $this
->morphMany(LoginLog::class, 'employable')
->latest();
}
}
I found another way to solve this issue...
class SomeModel extends Model
{
/**
* Polymorphic Relationships
*/
public function loginLog()
{
return $this->morphMany(LoginLog::class, 'employable');
}
public function show($token, $pagination = 0)
{
return self::where([
'token' => $token,
])->with([
'loginLog' => function ($query) use ($pagination) {
return $query->select([
'employable_id',
'ip',
'created_at',
'updated_at',
])
->skip($pagination)
->take(\Common::paginationLimit())
->orderBy('id', 'DESC');
}
])
->orderBy('id', 'DESC')
->first('id') ?? null;
}
}
Since I do not need the base table's parameters, therefore, I am fetching only id from it.
Also, with this way I am able to use the pagination too (I am using loadmore pagination).

Laravel error using with() method in Eloquent

I'm trying to call using with() method in Laravel Eloquent ORM, but getting the following error.
Argument 1 passed to
App\Http\Controllers\DashboardController::App\Http\Controllers\{closure}()
must be an instance of Illuminate\Database\Eloquent\Builder,
instance of Illuminate\Database\Eloquent\Relations\HasMany given
I'm using the latest version of Laravel 6. Any ideas what might have caused this?
Controller
class DashboardController extends Controller
{
public function __construct()
{
$this->middleware('auth:api');
}
public function formIndex(Request $request)
{
$id = auth()->user()->id;
$item = Groupe::find($id)->with(
[
'etudiants' => function (Builder $query) {
$query->select('id');
}
]
)->first();
return $item;
}
}
Model
class Groupe extends Authenticatable implements JWTSubject
{
public function etudiants()
{
return $this->hasMany('App\Etudiant');
}
}
The error comes from the type hint you put on the $query variable, as the error message said the object that gets passed in there is a relationship not a raw Query Builder. Just remove the type hint. Also ::find() executes a query, so you're be executing 2 queries, use the query below instead
Groupe::where('id', $id)->with(['etudiants' => function ($query) {
$query->select('id');
}])->first();
Additionally, you don't need to use the callback syntax to only eager load certain columns, the callback syntax is for putting contraints on which records get returned. Try this instead.
Groupe::where('id', $id)->with('etudiants:id,name,email')->first();
But what do you want return? groupe->students[]?? you can use
$item = Groupe::where('id',$id)->with('etudiants')->first();

Laravel 5.2 How to delete parent record from belongsTo relationship?

My Pricing model
protected $fillable = [
'zone_id',
'is_short_time',
'is_service_feeder',
'route_id',
'value',
];
public function route()
{
return $this->belongsTo(Route::class);
}
My Route Model
protected $fillable = [
'zone_id',
'from_city_id',
'to_city_id',
'is_in_the_city',
];
public function pricing(){
return $this->hasOne(Pricing::class);
}
Here is my controller
public function feeder_destroy($zoneid, $pricingfeederid)
{
$pricing_feeder = Pricing::find($pricingfeederid)->where('zone_id', $zoneid)->where('is_service_feeder', 1);
$pricing_feeder->route()->delete();
$pricing_feeder->delete();
}
The error says
Call to undefined method Illuminate\Database\Query\Builder::route()
I want to delete pricing record and route record too.
What wrong with my code? How should it's look like?
Any help appreciated.
Your controller should
$pricing_feeder = Pricing::find($pricingfeederid)->where('zone_id', $zoneid)->where('is_service_feeder', 1)->first();
Dont forget first() at the end.
Then use like so $pricing_feeder->route->delete();
Try this... $pricing_feeder->route->delete(); Removing () from route()
Your error is on the relation, not the Parent.
not the fanciest but you can delete the route that comes with pricing by adding this method to your route model
public function delete()
{
// delete all related pricing
$this->pricing()->delete();
// delete the route as well
return parent::delete();
}
then just call $pricing_feeder->route->delete();
Ok so I have this model relationships
In Post model
public function user(){
return $this->belongsTo(User::class);
}
In User model
public function post(){
return $this->hasMany(Post::class);
}
and the following code deleted all the posts and the user
$user = \App\User::findOrFail(1);
$user->post[1]->delete();
$user->delete();
Your code does not work, becouse you need to add a first() method call:
$pricing_feeder = Pricing::find($pricingfeederid)->where('zone_id', $zoneid)->where('is_service_feeder', 1)->first();
Than I'd check the returned object if is null. If is not, than you can delete the related relationship and the model as well.
Also, when calling the delete() methods use the relationships as follows:
$pricing_feeder->route->delete();

Resources