I am building an inventory system where there is users with different levels of authority changing fields. I am trying to change the "protected $allowedFields" class property within a function inside the model, but it will not allow me. Do I have to create 2 different models, or bake the authentication into the html code? Any advice would be appreciated.
class InventoryModel extends Model
{
protected $table = "tcg_main_inv";
protected $primaryKey = 'id';
protected $allowedFields = ['size'];
public function setInvFields(string $userLevel)
{
if ($userLevel == "admin") {
$allowedFields = ['container_number', 'size', 'dealer_cost', 'date_in',
'sales_order_number'];
} else if ($userLevel)
$allowedFields = ['date_in', 'sales_order_number'];
}
Note: this is just a snippet of my model code.
Thank you to #ViLar, I was able to figure out a solution that seems to work. I made a function inside the model that changes the allowed fields.
class InventoryModel extends Model
{
protected $table = "tcg_main_inv";
protected $primaryKey = 'id';
protected $allowedFields;
public function userAuth(string $user_type)
{
if($user_type == "dealer"){
$this->allowedFields = [ 'container_number'];
}
else if ($user_type == "admin"){
$this->allowedFields = ['size', 'container_number', 'dealer_cost'];
}
}
}
Related
anyone can help me here with a problem?
I'm creating one area in Laravel where Users can login accordingly to their role.
Used an artisan command to create the auth, quite straightforward so far.
Then, I started by changing the table name and the primary key of the table 'users' in the DB.
With this done, one needs to update the User Model (automatically generated by the artisan command) and let the model know where exactly is the table 'users' and which one is the primary key for that table.
protected $table = 'users';
protected $primaryKey = 'userID';
After this, once I go to the browser and do a normal login, it doesn't let me access the admin dashboard and I'm getting prompt with trying to get a property of a non-object.
This comes from the fact that once the table and the primary key are changed like I've done before, '$this' is not in object context anymore.
How can I make it work?
User.php:
class User extends Authenticatable
{
(...) public function isAdmin(){
if($this->roles->Role_Type == "Admin" && $this->is_active == 1){ //this one is the line 83 where the error is
return true;
}
return false;
}
(...)
}
You have error in this code
$this->roles->Role_Type
"$this->roles" returns the roles corresponding to that user and then you taken the field "Role_Type".
In your scenerio, there is no roles attached to that user.
So this "$this->roles" returns null.
So you could not take the value "Role_Type". This causes error.
You have to do the following
if($this->roles != null && $this->roles->Role_Type && $this->is_active == 1) {
return true;
} else {
return false;
}
Note: your code will work with has one relationship.
Class User extends Model
{
public function roles()
{
return $this->hasOne('App\Role');
}
}
If you want to use roles and permission in effecient manner, try this package https://github.com/romanbican/roles
It worked this way:
went to the DB and deleted the strong relationships (FKs) stablished between the tables, they're always a pain for Developers, requiring much more code just to have them there.
Thanks to you all for all the help and bellow is the code that used and worked fine:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
//
protected $table = 'users';
protected $primaryKey = 'userID';
protected $fillable = [
'name',
'email',
'password',
'roleID',
'photoID',
'is_active'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function role(){
return $this->belongsTo('App\Role', 'roleID');
}
public function photo(){
return $this->belongsTo('App\Photo', 'photoID');
}
// public function setPasswordAttribute($password){
//
//
// if(!empty($password)){
//
//
// $this->attributes['password'] = bcrypt($password);
//
//
// }
//
//
// $this->attributes['password'] = $password;
//
//
//
//
// }
public function isAdmin(){
if($this->role->Role_Type == "Admin" && $this->is_active == 1){
return true;
}
return false;
}
public function posts(){
return $this->hasMany('App\Post');
}
public function getGravatarAttribute(){
$hash = md5(strtolower(trim($this->attributes['email']))) . "?d=mm&s=";
return "http://www.gravatar.com/avatar/$hash";
}
}
I have a User-Roles model, using Laravel 4 where a user can have many roles, using Eloquent. I can access all roles linked to a user easily using this code :
class User extends Model {
protected $table = 'user';
protected $fillable = array('name');
public function rolesLinked() {
return $this->hasMany('App\UserRoleLink', 'user_id');
}
}
I've been trying to obtain the roles that are not linked to a user, to display on the specific user's page in a select box. Using this function, included in the User class.
public function rolesNotLinked() {
$user = this
$roles = Roles::whereDoesntHave('App\UserRoleLink',function($query) use ($user){
$query->where('user_id',$user->id);
});
}
The problem is, calling this function gives me the following error.
Call to undefined method Illuminate\Database\Query\Builder::App\UserRoleLink()
I've tried using has with < 1 to see if the function was problematic, but after reading this and the online source code, the function call pretty much does what I've tried.
Is something wrong in my function call, or have I messed up configurations somewhere?
For reference, here are my other Model classes:
class UserRoleLink extends Model{
protected $table = 'user_role_link';
protected $fillable = array('role_id','user_id);
public function role() {
return $this->hasOne('App\Role', 'role_id');
}
}
class Role extends Model{
protected $table = 'role';
protected $fillable = array('name');
}
EDIT: I've found out that I messed up by fillables when I copy-pasted. It didn't fix the issue, but I guess that's one step closer.
To use whereDoesntHave method, you must add the relation in your Role Model.
class Role extends Model{
protected $table = 'role';
protected $fillable = array('name');
public function UserRoles() {
return $this->hasMany('App\UserRoleLink', 'id');
}
}
Also, the whereDoesntHave method first parameter is not thte model but the function of the relation:
public function rolesNotLinked() {
$user = this
$roles = Roles::whereDoesntHave('UserRoles',function($query) use ($user){
$query->where('user_id',$user->id);
});
}
I'm new to laravel. I have 2 table
class Client extends Model
{
protected $fillable = ['name'];
public function clientmoreinfo()
{
return $this->hasMany('App\Moreinfoclient');
}
}
class Moreinfoclient extends Model
{
protected $table = 'clients_additionalfield';
protected $fillable = ['client_id', 'nameinput', 'valueinput'];
public function clients()
{
return $this->belongsTo('App\Client');
}
}
and i need to be able to add many additional fields at once as seen here:
this is how I add any number of entries, and more importantly, how do I update or remove them later?
thank you all in advance !
I'm having trouble figuring out how to access a nested relationship within Laravel. The specific example I have is a Movie that has many entires in my Cast table which has one entry in my People table. These are my models:
MOVIE
class Movie extends Eloquent {
protected $primaryKey = 'movie_id';
protected $table = 'movie';
// Relationships
public function cast()
{
return $this->hasMany('MovieCast', 'movie_id');
}
}
MOVIECAST
class MovieCast extends Eloquent {
protected $table = 'movie_cast';
public function person()
{
return $this->hasOne('Person', 'person_id');
}
public function netflix()
{
return $this->belongsTo('Movie', 'movie_id');
}
}
PERSON
class Person extends Eloquent {
protected $primaryKey = 'person_id';
protected $table = 'people';
public function movieCast()
{
return $this->belongsTo('MovieCast', 'person_id');
}
}
In my controller I can access the cast (containing person_id and role_id) like so:
public function movie($id)
{
$movie = Movie::find($id);
$cast = $movie->cast();
return View::make('movie')->with(array(
'movie' => $movie,
'cast' => $cast
));
}
...but I don't know how to access the corresponding name field in my People table.
EDIT 1:
Using the classes exactly as defined below in #msturdy's answer, with the controller method above I try to render the person names like so inside my view:
#foreach($cast->person as $cast_member)
{{$cast_member->person->name}}
#endforeach
Doing this i get the error:
Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$person
I don't know if it makes a difference or not but I have no id field on my People table. person_id is the primary key.
It should be simple, once you have accessed the cast...
Route::get('movies', function()
{
$movie = Movie::find(1);
$cast = $movie->cast;
return View::make('movies')->with(array(
'movie' => $movie,
'cast' => $cast));
});
Note: at this point, $cast is an instance of the Collection class, not a single object of the MovieCast class, as the
relationship is defined with hasMany()
you can iterate over it in the View (in my case /app/views/movies.blade.php
#foreach($cast as $cast_member)
<p>{{ $cast_member->person->name }}</p>
#endforeach
Class definitions used for testing:
class Movie extends Eloquent {
protected $primaryKey = 'movie_id';
protected $table = 'movie';
public $timestamps = false;
// Relationships
public function cast()
{
return $this->hasMany('MovieCast', 'movie_id');
}
}
class MovieCast extends Eloquent {
protected $table = 'movie_cast';
public $timestamps = false;
public function person()
{
return $this->hasOne('Person', 'person_id');
}
}
class Person extends Eloquent {
protected $primaryKey = 'person_id';
protected $table = 'people';
public $timestamps = false;
public function movieCast()
{
return $this->belongsTo('MovieCast', 'person_id');
}
}
I am using Laravel 4 and eloquent orm to build a movie session database.
Now I have the following Models.
class Location extends \Eloquent
{
public $timestamps = false;
public $table = 'movsys_location';
protected $fillable = array('name', 'desc');
public function sessions(){
return $this->hasMany('Session', 'location_id');
}
}
class Session extends \Eloquent
{
public $timestamps = false;
public $table = 'movsys_session';
protected $fillable = array('time');
public function location(){
return $this->hasOne('Location', 'id');
}
}
(Note: These models are stripped to the necessary code.)
Now in my controller, I have the following.
$Sessions = Session::all();
foreach($Sessions as $Session){
echo (isset($Session->location->name) ? $Session->location->name : 'NO LOCATION');
}
And this is what my database looks like:
Now, everything seems to work, but even though both sessions have the same location, ONLY the first session will return the name of the location! The second echo will return "NO LOCATION".
Any idea or help as to why would be appreciated. If this answer isnt clear enough let me know.
Try this one in place of yours:
class Session extends \Eloquent
{
public $timestamps = false;
public $table = 'movsys_session';
protected $fillable = array('time');
public function location(){
return $this->belongsTo('Location');
}
}