laravel-permission: assignRole works in Tinker but not in application - laravel-5

See my AdministrationController.php below:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Illuminate\Foundation\Auth\User;
class AdministrationController extends Controller
{
public function index() {
$user = User::find(1);
$role = Role::where('name', 'owner')->get()->first();
$user->assignRole($role);
}
}
This is the important part of my User model:
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use HasRoles;
use Notifiable;
...
}
Curiously, the line $user->assignRole($role); in AdministrationController.php fires the following error:
BadMethodCallException
Method Illuminate\Database\Query\Builder::assignRole does not exist.
However, in Tinker this command sequence works fine and effects the desired result:
>>> $user=User::find(1)
>>> $role=Spatie\Permission\Models\Role::where('name', 'owner')->get()->first()
>>> $user->assignRole($role)
I googled for this issue, tried some fixing proposals but nothing helped me out. What's wrong in my AdministrationController.php / User.php?

Okay, I just could fix it. so simple when you know it. In AdministrationController.php, I replaced use Illuminate\Foundation\Auth\User; with use App\User;. That's it...

Related

Call to undefined method Auth::user()->can() in laravel 8 error

I have a problem with determining the permission with Auth::user()->can().
For example Auth::user()->can('trunk.index) returns always error;
But I have a problem.
If I dump $user->getPermissionsViaRoles(); ,I will get a large result.
I'm using different table user_view table.
And according to it I have changed in Auth.php file. and login is working fine.
'providers' => [
'users' => [
'driver' => 'self-eloquent',
'model' => App\Models\UserView::class,
]
],
But when I try to check permission the via Auth::user()->can('trunk.index) then it gives error below error.
Call to undefined method App\\Models\\UserView::can()
Below is my UserView model code.
<?php
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Traits\HasRoles;
use Laravel\Lumen\Auth\Authorizable;
use Laravel\Sanctum\HasApiTokens;
class UserView extends Model implements AuthenticatableContract
{
use Authenticatable;
use HasFactory;
use HasRoles;
use HasApiTokens;
protected $table = 'user_view';
protected $primaryKey = "user_id";
protected $fillable = [
'username', 'password',
];
protected $guarded = [];
public function getAuthPassword()
{
return ['password' => $this->attributes['user_password']];
}
// public function can($abilities, $arguments = []) {
// }
}
help me if I'm missing something. Thank you.
You are using a custom User model which does not implement the \Illuminate\Contracts\Auth\Access\Authorizable interface and \Illuminate\Contracts\Auth\Access\Gate\Authorizable trait. You do actually have an import for this interface, but it is not used anywhere.
Also be careful about the existing import Laravel\Lumen\Auth\Authorizable. I'm not familiar with Lumen, but this might be a different implementation / wrong import.
You essentially need to update your model with the following two lines:
<?php
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Foundation\Auth\Access\Authorizable; // <-- add import
use Spatie\Permission\Traits\HasRoles;
use Laravel\Sanctum\HasApiTokens;
class UserView extends Model implements AuthenticatableContract,
AuthorizableContract // <-- add interface
{
use Authenticatable;
use Authorizable; // <-- add trait
use HasFactory;
use HasRoles;
use HasApiTokens;
// ... other code ...
}

Laravel: undefined method timeline

I am extending the Tweety application from Laracast.com. I run info a problem that I struggle to find the source of. (Btw I am using VS Code).
The request handler in web.php:
Route::middleware('auth')->group(function() {
Route::get('/tweets', 'TweetsController#index')->name('home');
The index method in the tweetscontroller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Tweet;
class TweetsController extends Controller
{
public function index()
{
return view('tweets.index', [
'tweets' => auth()
->user()
->timeline(),
]);
}
In my problems window I get the warning:
Tweetscontroller.php app\Http\Controllers
Undefined method 'timeline'. intelephense(1013) [17,19]
But the timeline method is defined in the User model:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable, Followable;
public function timeline()
{
$friends = $this->follows()->pluck('id');
return Tweet::whereIn('user_id', $friends)
->orWhere('user_id', $this->id)
->withLikes()
->orderByDesc('id');
}
If I login to the aplication I get the error message:
Facade\Ignition\Exceptions\ViewException
Call to undefined method Illuminate\Database\Eloquent\Builder::links() (View: C:\xampp\htdocs\tweety\resources\views\__timeline.blade.php)
Anyone a good suggestion?
Kind regards,
HUbert

Issue with Laravel Notifications

I have a problem with Laravel notifications. I try to give a user notification about something, but Laravel cannot find notification class.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
class NotificationController extends Controller
{
public function getNot(Request $request)
{
$user = Auth::user();
$user->notify(new NewPost('a'));
}
}
I've also created a notification with the name NewPost.php, the problem is:
Class 'App\Http\Controllers\NewPost' not found
this one, so in the User model already included Notifications and notifiable.
Add use statement before class definition.
use Illuminate\Http\Request;
use Auth;
use App\Notifications\NewPost;
I assume that you create notification by artisan, if no, then keep in mind that namespace could be different.

how to extend Builder class in laravel 5.2

I tried to extend Illuminate\Database\Query\Builder to override various functions, but i cant make it.
I created a custom builder (CustomBuilder.php)
<?php
use Closure;
use Illuminate\Support\Collection;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\Query\Grammars\Grammar;
use Illuminate\Database\Query\Processors\Processor;
class CustomBuilder extends Illuminate\Database\Query\Builder {
public function get($columns = ['*'])
{
$builder = $this->applyScopes();
$models = $builder->getModels($columns);
if (count($models) > 0) {
$models = $builder->eagerLoadRelations($models);
}
return $builder->getModel()->newCollection($models);
}
}
And a custom model (CustomModel.php)
<?php
use DateTime;
use ArrayAccess;
use Carbon\Carbon;
use LogicException;
use Illuminate\Events\Dispatcher;
use Illuminate\Database\Eloquent\Relations\Pivot;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Support\Contracts\JsonableInterface;
use Illuminate\Support\Contracts\ArrayableInterface;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
// use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\ConnectionResolverInterface as Resolver;
use CustomBuilder as QueryBuilder; // MyModel should now use your MyQueryBuilder instead of the default which I commented out above
abstract class CustomModel extends Illuminate\Database\Eloquent\Model
{
}
?>
What is the correct folder to put these files, and how to call it from my models?
I tried in app/Extensions, in vendor, but i get the same error.
Class CustomModel cannot be found.
Thanks

Can't validate user attempt

I'm using laravel 5.0 and I can't validate the login.
If I type a wrong match of email/pass, it redirects me perfect.
But when I type a correct email/pass then it returns me this:
Argument 1 passed to Illuminate\Auth\EloquentUserProvider::validateCredentials() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\User given ...
I'm following the documentation and it looks like everything is allright.
Model:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
}
Controller
public function postsignin(Request $request)
{
if( Auth::attempt( ['email' => $request['email'], 'password' => $request['password'] ] ) )
return redirect()->route('dashboard');
return redirect()->back();
}
No idea what it is.
try to implement the AuthenticatableContract and Authenticatable trait
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
class User extends Model implements AuthenticatableContract{
use Authenticatable
}

Resources