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
Related
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
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;
}
*/
}
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'm creating a school platform where students, teachers,... can login using their credentials. To reduce duplicate data I did not make a separate table called students, instead I keep all the data in the users table.
To know if a user is a student I a have a table that is called enrolments, in this table a user_id , schoolyear_id and class_id is stored.
I already made a student model that refers to the users table, but how can I ensure that this model only passes students?
EER:
Student.php:
<?php
namespace App;
class Student extends User
{
protected $table= 'users';
public function enrollments(){
return $this->belongsToMany(Enrollment::class);
}
}
User.php:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Support\Facades\Auth;
class User extends Authenticatable
{
use Notifiable;
use HasRoles;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name','last_name', 'password'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function profiles(){
return $this->hasOne(Profile::class);
}
}
What I want to achieve is that when I call the Student::all(); function I get all the users who are enrolled in the school,hence students.
Check out model events: https://laravel.com/docs/5.5/eloquent#events
You should be able to drop this into your student model for a test:
protected static function boot(){
parent::boot();
static::retrieved(function($thisModel){
if($thisModel->isNotAStudent or whatever logic you need){
return false;
}
}
}
I'm still on 5.4, which does not have the retrieved model event built in, but returning false generally stops the call from going through. So applying that logic to the retrieved event may stop that model instance from being returned if it is not a student, but allow students to be returned. Just a thought.
Your provided solution lead me in the right direction. My problem is solved by using global scope:
<?php
namespace App;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
class Student extends User
{
protected $table= 'users';
protected static function boot()
{
parent::boot();
static::addGlobalScope('student', function (Builder $builder) {
$builder->whereExists(function ($query) {
$query->select(DB::raw(1))
->from('enrollments')
->whereRaw('enrollments.user_id = users.id');
});
});
}
public function enrollments(){
return $this->belongsToMany(Enrollment::class);
}
}
I want to use the User model that already in the app folder. but it seem it only extends Authenticatable and can't extend by the model Class i want to use it as a link to the other class, like user has only one employee. what else can i do to recycle the user model that is already extended by Authenticatable?
thanks for the help :)
this is the user model that extends the authenticatable
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function employee()
{
return $this->belongsTo('App\Employee');
}
}
And this is the employee model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
// protected $table = "positions";
// public function position()
// {
// return $this->hasMany('App\Position');
// }
protected $table = "employees";
public function employee()
{
return $this->hasOne('App\User');
}
}
It already inherited Model class. If you follow Illuminate\Foundation\Auth\User you will finally find that it is inherited from a Model class. So, your User model has the same features that your other models have.