We have created a format where user can be assigned with role and each role have specific permissions. We are using laravel spatie permission library.
When trying to get the permission assigned to user or not it state the error as below:
Error :
Call to a member function contains() on string {"userId":1,"exception":"[object] (Error(code: 0): Call to a member function contains() on string at C:\\xampp\\htdocs\
olesPermission\\itm-encode\\vendor\\spatie\\laravel-permission\\src\\Traits\\HasPermissions.php:288)
[stacktrace]
Code :
public function index(){
$user = User::find(auth()->user()->id);
dd($user->hasPermissionTo('Ticket-Handler-Wise'));
return view('roles_permission.new_index');
}
same error is on blade when tryng to access the permission with can. Can anyone help that how we can acheive this.
User Model:
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\Group;
use Storage;
use DB;
use stdClass;
use Carbon\Carbon;
use Exception;
use Log;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use Notifiable;
use SoftDeletes;
use HasRoles;
protected $guarded = [];
protected $hidden = [
'password', 'remember_token',
];
**Permission.php : **
<?php
return [
'models' => [
/*
* When using the "HasPermissions" trait from this package, we need to know which
* Eloquent model should be used to retrieve your permissions. Of course, it
* is often just the "Permission" model but you may use whatever you like.
*
* The model you want to use as a Permission model needs to implement the
* `Spatie\Permission\Contracts\Permission` contract.
*/
'permission' => Spatie\Permission\Models\Permission::class,
** blade.php : **
#section('content')
<section class="content">
#can('Ticket-Handler-Wise')
hello
#else
No
#endcan
Related
I want to create a model for my project but i don't know what's the different between the original MVC style and laravel default auth model
there's a directory different too. The original MVC was in Model folder, while the defaulth auth is in controller folder. I don't know why make a model inside the Controller folder
This is the code that's work ( laravel default auth model )
source : https://www.5balloons.info/changing-authentication-table-laravel/
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class CustomUser extends Authenticatable
{
use Notifiable;
protected $table = 'customusers';
protected $fillable = [
'name','username','email','passcode','active'
];
protected $hidden = [
'passcode',
];
}
while this code is not work with error Class 'App\Models\Authenticatable' not found
i can create a work around to use the class, but i need to understand why
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class TestUser extends Authenticatable
{
use HasFactory, Notifiable;
protected $table = 'testuser';
protected $fillable = [
'username','password',
];
protected $hidden = [
'password',
];
/*
public funtion getAuthPassword()
{
return $this-> passcode;
}
*/
}
need help laravel. I have 2 model in different folder
app\User
app\model\Role
there is no problem when i used at UsersController -> call app\User, or RolesController -> call app\model\Role
but, when i used both models on UsersController , the app\model\Role didnt work
==================== UsersController ======================
namespace App\Http\Controllers\admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use app\User;
use app\model\Role as Role;
use DataTables;
class UserController extends Controller
{
public function index(Request $request){
$data['title_page'] = 'User';
$data['roles'] = Role::all(); // this line show error
return view('admin/user', $data);
}
}
======================== app\model\Role ===================
namespace App\model;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
protected $fillable = ['id','name'];
protected $tables = 'roles';
public function users(){
return $this->belongsTo('App\User','role');
}
}
======================== app\User =======================
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $table = "users";
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','role', 'status'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function roles(){
return $this->hasOne('App\model\Role','id');
}
}
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Class 'app\model\Role' not found
Try with capital 'A' on 'App'. Some systems are case sensitive. So use App\Model\Role depending on your folder name for model. IE if your model folder is lower case, match it in the use statement.
Also, you don't need the as keyword here unless there are conflicts - you may be fine with just use App\Model\Role without the as Role.
One more item, make sure the Role class is actually in the model folder and that your namespace is at the top of the php file correctly referencing the App\Model namespace. So in your Role class make sure the caps match your use call -
<?php
namespace App\Model
I wanted to relate a profile model to the existing user model using the relationship belongs to and hasOne and I am getting that error.
here is my Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
public function user(){
return $this->belongsTo(User::class);
}
}
User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Symfony\Component\HttpKernel\Profiler\Profile;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'username', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function profile()
{
return $this->hasOne(Profile::class);
}
}
In my terminals i can get the user through the profile but cannot get the profile using user. here is the error
$user->profile
TypeError: Too few arguments to function Symfony/Component/HttpKernel/Profiler/Profile::__construct(), 0 passed in /Users/macair13/freeCodeGram/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php on line 720 and exactly 1 expected.
To fix the issue, replace the use Symfony\Component\HttpKernel\Profiler\Profile; line on top of your User.php file with use App\Profile; instead.
This is happening as you've mistakenly included the wrong class on top of your User.php file. When Laravel is trying to load the relationship, it attempts to construct a Symfony\Component\HttpKernel\Profiler\Profile object instead of constructing your intended model.
Use like below in your user model
public function profile()
{
return $this->hasOne('App\Profile', 'foreign_key');
}
I am not sure why you have used Symfony\Component\HttpKernel\Profiler\Profile in your user model. When your relationship is building it is using that Profile and not your Profile Model. You have to use the Profile Model namespace while defining the relationship.
I wanna try to make test, member who logged in can create a job, this is my test code.
/** #test */
public function member_can_create_a_job(){
$member = factory('App\Models\M_member')->create();
$this->actingAs($member);
$job = factory('App\Models\M_lowker')->make();
$this->post('/lowker/tambah-lowker', $job->toArray())->assertRedirect('/lowker/tambah-lowker');
}
This is my App\Models\M_member
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class M_member extends Model{
protected $table = "member";
public $timestamps = false;
protected $fillable = ["nama", "email", "password", "alamat", "tgl_lahir", "remember_token"];
public function jobs()
{
return $this->hasMany('App\Models\M_lowker');
}
public function comments()
{
return $this->hasMany('App\Models\M_komentar');
}
}
When I run, I get error in cmd like
this.
1) Tests\Feature\JPSTest::member_can_create_a_job TypeError: Argument 1 passed to Illuminate\Foundation\Testing\TestCase::actingAs() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\Models\M_member given, called in I:\W 42 N\Home Work\Semester 5\Rekayasa Perangkat Lunak\Praktikum\jps\tests\Feature\JPSTest.php on line 35
I:\W 42 N\Home Work\Semester 5\Rekayasa Perangkat Lunak\Praktikum\jps\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\InteractsWithAuthentication.php:16 I:\W 42 N\Home Work\Semester 5\Rekayasa Perangkat Lunak\Praktikum\jps\tests\Feature\JPSTest.php:35
ERRORS! Tests: 3, Assertions: 3, Errors: 1.
This error tells you that the model which you are using is not extending the Illuminate\Contracts\Auth\Authenticatable contract, which is necessary to use the actingAs method. If you have laravel's auth you can check the user model as an example of this . Which is something like:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
So, try extending your model to have this functionality.
or you can implement the Authenticatable contract on your model like this
class User extends Model implements
AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
}
You can add first() when you create user
$user = factory('App\User')->create()->first();
This problem solved with modify my M_member model like this.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Auth\Authenticatable as AuthenticableTrait;
class M_member extends Model implements Authenticatable{
use AuthenticableTrait;
I'm trying to build my first Laravel application by following a few guides on the internet and I'm feeling I'm missing something obvious. Here is the code.
Error
BadMethodCallException in Builder.php line 2450: Call to undefined
method Illuminate\Database\Query\Builder::addresses()
User-Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Sentinel;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'email', 'password',
];
protected $hidden = [
'password',
'remember_token'
];
public function addresses()
{
return $this->hasMany('App\CustomerAddress');
}
}
CustomerAddress-model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CustomerAddress extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
CustomerAddress-controller
<?php
namespace App\Http\Controllers;
use App\CustomerAddress;
use Illuminate\Http\Request;
class CustomerAddressController extends Controller
{
public function create(Request $request)
{
$address = new CustomerAddress();
$address->address = $request['address'];
$request->user()->addresses()->save($address);
}
}
Error appears after this piece of code:
$request->user()->addresses()->save($address);
Any ideas? Thanks and cheers
In .config/cartalyst.sentinel.php, change 'model' => 'Cartalyst\Sentinel\Users\EloquentUser' to 'model' => 'App\User' to use your user model with the addresses relation defined
In ./app/User change User extends Authenticatable to User extends \Cartalyst\Sentinel\Users\EloquentUser to extend sentinel's user to your app's User model
Finally, your controller code should now be
`$address = new CustomerAddress();
$address->address = $request->input('address');
$request->user()->addresses()->save($address);`
and everything should be peachy