Laravel 4 BadMethodCallException upon calling a method of a model - php

I created a User class in Laravel application as follows:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
...
public function hasAnyRoles()
{
return true;
}
The function there is simplified to always return true for the purposes of this example. I pretty much followed this tutorial here to create this class: http://alexsears.com/article/adding-roles-to-laravel-users. I created a controller next as follows:
class WelcomeController extends Controller
{
public function welcomeAction()
{
$user = User::find(Auth::user()->id);
$result = $user->hasAnyRoles();
return Response::make("Result: ".$result);
}
}
I'm able to successfully login to the system, routes are working as intended, the variable $user is correctly initialized and I can get all the information out of it (username, id, email, etc.) but once I call the $user->hasAnyRoles() method I get:
BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::hasAnyRoles()
If I comment out the respective line in the controller it all works but I cannot call any method of that model without getting that error. Any ideas why this is happening?

As stupid as it is, it turns out that the application was reading the User class from a different file. I had a User_backup.php copied in the same directory just in case and this was the file that the class was read from so any changes to User.php were disregarded. I had to remove the backup file and do a composer update in order to get it all working correctly..

Related

Laravel Befriended revoke method not working

I'm trying to remove a follower but the revokeFollower() method returns nothing and not working. Using the Laravel Befriended https://github.com/renoki-co/befriended package.
public function unfollowFollowers(Request $request){
$loginUser = Auth::user();
return $loginUser->revokeFollower($request['id']);
}
User.php
use Rennokki\Befriended\Traits\Follow;
use Rennokki\Befriended\Contracts\Following;
use Rennokki\Befriended\Scopes\FollowFilterable;
class User extends Authenticatable implements Following
{
use Notifiable,Follow,FollowFilterable;
}
On the README there is mentioned:
Note: Following, unfollowing or checking if following models that do not correctly implement CanBeFollowed and Followable will always return false.

Load user settings with Laravel 5.6

I'd like to be able to modify the Auth->user() data that Laravel 5.6 uses. I have table called settings with a column called user_id in it that corresponds to a user id.
I tried modifying app\User.php and adding a __construct function:
public function __construct() {
$this->settings = Settings::where('user_id',
Auth->user->id()
)->first();
}
And I created a file app\Settings.php with the following:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class settings extends Model
{
protected $table = "settings";
}
However I'm getting a user error on the Auth->user()->id line in User.php, although I'm sure thats the correct way to reference it?
How can I load the data from the settings table to the User class?
You can just use load() method to lazy load the relation:
auth()->user()->load('settings');
You need to do this just once per request, in a middleware for example. Then you'll be able to use the data in any part of your app:
{{ auth()->user()->settings->theme }}
Of course, to make this work you need to define relationship in the User model, for example:
public function settings()
{
return $this->hasOne(Settings::class);
}

Trying to get property of non-object in laravel 5.3 app though model relations seems appropriate

User model
class User extends Authenticatable{
public function enrollments() {
return $this->hasMany('App\enrollments','user_email');
}
}
Batch model
class batch extends Model{
protected $table = 'batch';
public function enrollments() {
return $this->hasMany('App\enrollments');
}
}
Enrollments model
class enrollments extends Model{
public function batch() {
return $this->belongsTo('App\batch');
}
public function user() {
return $this->belongsTo('App\User','email');
}
}
if I use $enrollment->batch->title, it works..
but if I use $enrollment->user->name, it gives an error
Trying to get property of non-object
Please help, I am stuck
Thanks in advance
EDIT
The problem arose after I changed the foreign key from between user and enrollment from id to email and renamed my column to user_email from user_id. Before that code was working fine.
Solved
Got the problem, It was with some data in enrollment which didn't have registered email with user.
This code will note work simply because User is not a child of Model. To fix it you must extend from Model. Authenticatable is an interface and there is an equivalent trait; there is no such class.
You must implement the interface if you want your user class to be Authenticatable. But to answer your question, extend the base model, Model.
class User extends Model {
public function enrollments() {
return $this->hasMany('App\enrollments','user_email');
}}
In addition:
If you need to log an existing user instance into your application,
you may call the login method with the user instance. The given object
must be an implementation of the
Illuminate\Contracts\Auth\Authenticatable contract. Of course, the
App\User model included with Laravel already implements this
interface:
https://laravel.com/docs/5.3/authentication

laravel 5 method does not exist - why can't i access my function?

I am having trouble calling a method in my Account class.
Here is the method defined in my class:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Account extends Model
{
protected $fillable = ['customer_id','bookmaker_id', 'balance', 'profit'];
public function addProfit($amountToAdd) {
$this->profit = $this->profit + $amountToAdd;
}
.......
......
Here is my method call in my controller
$account->addProfit(5);
I have established that I am returning a single account record with the dd($account) command, so it appears it's definitely a problem with the method.
However, I get this message when I try to run the code:
BadMethodCallException in Macroable.php line 81:
Method addProfit does not exist.
In case someone encounters the same issue, Laravel will only call the Model's method if called on one single object. If you have created a custom function in your Model.php file called getAge on a User model, for instance, you have to make sure that in the expression $object->getAge(), $object is one object. This is where using ->first() instead of just ->get() becomes relevant

Call to undefined method after creating new model (Laravel 4.2)

I just set up a new model and I am trying to call a custom written static method that I've written from inside a new controller to match the model:
<?php
class NewModelWebController extends AjaxController {
public function newModelView() {
$loggedUser = Auth::user();
$data['user'] = $loggedUser;
$data['allDetails'] = NewModel::getFullWithDetails($loggedUser->user_id);
return View::make('webApp::new-model.view', $data);
}
}
Here is the method definition inside the model class (there are no spaces before the php declaration):
<?php
class NewModel extends Eloquent {
protected $table = 'new_models';
protected $primaryKey = 'new_model_id';
public static function getFullWithDetails($userId) {
return 1; // doesn't matter what I return -- the problem still happens
}
}
The error that is returned is the following:
Call to undefined method Illuminate\Database\Query\Builder::getFullWithDetails()
When I make calls such as NewModel::find(1); it works with no issues, but once I try to make calls on the method I wrote, it does not work.
I tried all of the following commands with no success:
composer update
composer dump-autoload
composer clear-cache
chown -R www-data:www-data ./theProjectFile
Thoughts are appreciated.
Try using scopes instead of actual static methods.
class NewModel extends Eloquent {
public function scopeGetFullWithDetails($userId)
{
//
}
}
Calling is the same. NewModel::getFullWithDetails(1);
I ended up having to recreate the model from scratch. There must have been a problem with file encoding or filetype when I initially created it because originally I just duplicated another model class and then changed the values inside. Creating a brand new file and then pasting the PHP content back in fixed the issue! Thanks for the help!

Categories