BadMethodCallException in Builder.php: Call to undefined method Laravel 5.0 - php

As the title says I'm getting an error in Laravel 5.0 whilst trying to upgrade a Laravel 4.2 application.
The exact error message is: Call to undefined method Illuminate\Database\Query\Builder::orders()
I get the error when I try to fetch an authenticated users orders from a controller with the following line:
$this->user->orders()->orderBy('created_at', 'desc')->get()
A parent class sets $this->user as:
$this->user = Auth::user();
The user models relationship to orders is:
public function orders()
{
return $this->hasMany('App\Models\Order');
}
To confuse me even more $this->user->orders() returns the error I'm experiencing where as User::whereId($this->user->id)->first()->orders() returns the orders I was expecting.
When I dump both $this->user->orders() and User::whereId($this->user->id)->first()->orders() I get exactly the same output on screen.
Can anyone explain this and possibly point me towards the correct way to do this as my solution feels hacky and I'm sure there is a much cleaner way to accomplish what I'm trying to do.
Thanks

Apologies for answering my own question again, however I have found the proper soloution to my issue.
I had left the default User model in the App folder since installing Laravel 5, and this is the user model Laravel was using when I called Auth::user().
I needed to change config/auth.php to use my customised User Model and all is working as expected.

Related

Problem with spatie/laravel-menu and spatie/laravel-persmissions

I'm using spatie/laravel-menu and spatie/laravel-persmissions in my laravel project.
I have created a permission, assigned it to a role, and assigned the role to my user. This works fine.
Then I have generated a menu the middleware way using a macro like so:
\Menu::macro('main', function () use ($request) {
return \Menu::new()
->withoutWrapperTag()
->withoutParentTag()
->setActiveClassOnLink()
->route('preparation', 'Anstehende Termine')
->route('postprocessing', 'Nachbereitung')
->routeIfCan('administrate', 'protocols', 'Protokolle')
->addItemClass('nav-link')
->setActive($request->url());
});
In my application I have two User models with different connections:
App\User; using connection_a with database db_a and
App\DirectoryA\User; using connection_b with database db_b
In the auth config the first one is defined, and using Auth::user()->can('administrate') works fine, even in the Middleware that defines the menu.
Since I have added the menu item via routeIfCan, I'm getting an error. It tells
Base table or view not found: 1146 Table 'db_b.permissions' doesn't exist (SQL: select permissions.*, model_has_permissions.model_id as pivot_model_id, model_has_permissions.permission_id as pivot_permission_id, model_has_permissions.model_type as pivot_model_type from permissions inner join model_has_permissions on permissions.id = model_has_permissions.permission_id where model_has_permissions.model_id = 1 and model_has_permissions.model_type = App\User)
What is going wrong here? It should use the App\User model. Placing a dd() at the point the framework throws the exception shows me the correct connection...
Please help.
this mean table permissions not exist on your database maybe you forgot to run php artisan migrate after install laravel-permission?
A member of spatie helped to solve the problem:
Under the hood, routeIfCan calls app(Gate::class)->allows($ability, $ablityArguments). I assume Gate behaves slightly different than Auth::user() when it comes to multiple guards.
I don't see much room in routeIfCan to add an additional $guard or $connection argument, so I suggest you use $menu->addIf(Auth::user()->can('administrate'), ...) instead.

wasRecentlyCreated and wasChanged are not working

I am trying to use wasChanged and wasRecentlyCreated of models in laravel project but both of them are false in the below code
$saved=$project->accessInfo()->updateOrCreate(['type'=>$request->type],['value'=>$data]);
dd($project->accessInfo[0]->wasChanged(),$project->accessInfo[0]->wasRecentlyCreated,$project->wasRecentlyCreated,$project->wasChanged());
//here is my relation in Project model
public function accessInfo()
{
return $this->hasMany('Modules\Project\Models\ProjectAccessInfo', 'project_id');
}
also below code returns error
dd($project->accessInfo->wasChanged(),$project->accessInfo()->wasRecentlyCreated)
//No such method or attribute in both cases
//Call to undefined method Illuminate\\Database\\Eloquent\\Relations\\HasMany::wasChanged()
Thanks in advance for your help.
getChanges - Get the attributes that were changed.
getDirty - Get the attributes that have been changed since last sync.
When you want to know if the model has been edited since it was queried from the database, or isn't saved at all, then you use the ->isDirty() function.

how can do a multiple has() /orHas() in laravel 5.4 orm

First of all I should say I want to Use laravel ORM not query builder and not the Raw sql methods. so here is my question.
I have a model called bots that has belongTo(User::class) relation and 6 hasMany(TextPost::class) - hasMany(PhotoPost::class) and so on. I want to get bots that has at least one record in any of the hasMany(...) relations. so if a bot has a record in TextPost it should be returned and if a bot has no post in none of the hasMany(...) relations it should not be returned.
so far I have something like this in my User model
public function broadCasters()
{
return $this->bots->has('text_post')->orHas('photo_post')->orHas('media_post')->orHas('video_post')->orHas('audio_post')->orHas('document_post');
}
but its not going to work and says Call to a member function orHas() on boolean
so I wanted to change it to something like this:
public function broadCasters(){
return $this->bots->where(function($query){
return $query->has('TextPost')->orHas('PhotoPost') ...;
});
}
but this is not gonna work either and says Missing argument 2 for Illuminate\Support\Collection::where(). what should I do?
I use laravel 5.4. bu I saw this Question whereHas on multiple relationships - laravel 5.4 and its pretty close to what I want but no answers yet!!
also this question is another of my questions too, Combining AND/OR eloquent query in Laravel
but its not working either.
AND NOW THIS IS EXACTLY WHAT I WANT BUT NOT WORKING, I THINK BECAUSE ITS FOR LARAVEL 4 AND I USE LARAVEL 5.4
Laravel eloquent multiple has and where clause
enter code hereIf you user $this->bots, the result will be laravel collection array. You need to use $this->bots() like this :
public function broadCasters(){
return $this->bots()->where(function($query){
return $query->has('TextPost')->orHas('PhotoPost') ...;
})->get();
}

Upgrading to Yii2, ORM not functional

I'm upgrading a big project form Yii1 to Yii2. I'm having some problems regarding to ORM.
I have several relation declared in the following fashion(basically a copy-paste from the guidebook):
class Order extends \yii\db\ActiveRecord {
/* other code */
public function getAffiliate()
{
return $this->hasOne(Affiliate::className(), ['id_affiliate' => 'affiliate_id']);
}
Whenever I try to echo or w/e $order->affiliate->name; I get the following error:
yii\base\ErrorException: Trying to get property of non-object
I've got no experience with Yii1 what so ever. Something weird about this project is the database. All tables start with yii_tablename and id's are: id_tablename. Was that normal for Yii1 and could this be causing the issue above?
Edit: When I execute the function like so: $order->getAffilate() it returns an ActiveQuery WITHOUT the data from the affiliate.
When I execute the following:
$order->getBillingAddress()->one();
I get a weird error:
Getting unknown property: app\models\Order::billing
return $this->hasOne(Affiliate::className(), ['id_affiliate' => 'affiliate_id']);
It's mean that when you call $order->affiliate yii2 will find in Affiliate table on id_affiliate field current Order affiliate_id value and selected one value.
Check that you have right field names and database have right data.
When you call $order->affiliate you will get Affiliate object. But if you call $order->getAffiliate() you will get ActiveQuery object.
I found a solution. One which I don't really like though, but it does the job. Was reading this thread: link.
Kartik V
The problem is clearly in uniqueness in naming your relation and your model attribute. In your User model, you have an attribute named role and you also have a relation getter named getRole.
So I changed the name of the getter like so:
public function getOrderAffiliate()
{
return $this->hasOne(Affiliate::className(), ['id_affiliate' => 'affiliate_id']);
}
And that fixed the issue. Never had this issue before and wonder why this happened though.

Laravel 5 - Error accessing many-to-many data

In a Laravel 5 app, I have a "User" model and a "Permission" model, both with corresponding tables, that have a many-to-many relationship. There is a pivot table as well: "permission_user".
The User model contains the following method:
public function permissions()
{
return $this->belongsToMany('App\Permission');
}
And the Permission model contains the following method:
public function users()
{
return $this->belongsToMany('App\User');
}
I have been accessing user permissions in custom middleware with the following code, and it's been working splendidly until today.
$permissions = \Auth::user()->permissions()->get();
All of a sudden, this is breaking. I get the following error:
ErrorException in BelongsToMany.php line 177: Argument 1 passed to
Illuminate\Database\Eloquent\Relations\BelongsToMany::hydratePivotRelation()
must be of the type array, object given, called in
/Server/sites/app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
on line 158 and defined
Really not sure what's going on here. In an attempt to follow the docs more closely, I also tried this:
foreach (\Auth::user()->permissions as $permission)
{
// do something with $permission
}
But I get the same thing (the stack trace shows that the lines shown here are the last ones executed before heading into the Laravel source). I did update Laravel with Composer around the time this happened, but thought it unlikely that something in Laravel source has caused the problem. Can anyone see what I might be doing wrong here, and how I can fix it?
Sit tight, I believe this might actually just a current bug with Laravel 5 (which is still technically in alpha, so breaking changes are to be expected).
Taylor Otwell (the creator of Laravel) tweeted this earlier:
https://twitter.com/taylorotwell/status/553262692426059776
However, it looks like several parts of Laravel 5 core still need to be updated to be compatible with this change.
If you need your app to work right now, just change this in your composer.json file:
"laravel/framework": "~5.0",
to this:
"laravel/framework": "dev-master#9b108d85ce19300dfdd479fa4e05d9ea6e4e3abc",
And then run a composer update. This will pull in yesterdays version of Laravel 5, which was working.
Don't forget to change it back though once this is fixed!

Categories