return specific Data using has Role - php

My Code Here is Working Fine but although he is returning user Role in the return can i prevent user roles from returning it's belongs to relation using role_id in users Table
$paths = Path::with(['user','tags'])->where('category_id',1)->get();
foreach($paths as $path){
if($path->user->hasRole('admin')){
$AdminPaths [] = $path;
}
if($path->user->hasRole('user')){
$UserPaths [] = $path;
}
}
return $UserPaths;
My User Model
class User extends \TCG\Voyager\Models\User
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'username'
];
/**
* 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',
];
}

You are calling the function hasRole from here:
https://github.com/the-control-group/voyager/blob/1.2/src/Traits/VoyagerUser.php
It executes loadRolesRelations() that loads the roles relationships and thats why users come with the role relation loaded.
You could just unset the role relation after checking the role like:
foreach($paths as $path){
if($path->user->hasRole('admin')){
$AdminPaths [] = $path;
}
if($path->user->hasRole('user')){
$UserPaths [] = $path;
}
unset($path->user->role);
}

Related

SQLSTATE[42P01]: Undefined table when try to create new user

i'm new in laravel php and i try to create a new user with api post request and when i send this request i have a porblem when i do it
I use psgql and laravel 9. i use that
link to do this and custom somthing
This is my code:
i has User model like
class User extends Authenticatable
{
use HasApiTokens,HasFactory, Notifiable;
public $timestamps = false;
protected $table = 'user';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'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',
];
}
and here is my AuthController to create new user
class AuthController extends Controller
{
/**
* Create User
* #param Request $request
* #return User|\Illuminate\Http\JsonResponse
*/
public function createUser(Request $request){
try{
$validateUser = Validator::make($request->all(),[
'first_name'=>'required',
'last_name'=>'required',
'email'=>'required|email|unique:users,email',
'password'=>'required'
]);
if($validateUser->fails()){
return response()->json([
'status'=>false,
'message'=>'validation error',
'errors'=>$validateUser->errors()
],401);
}
$user = User::create([
'first_name'=>$request->first_name,
'last_name'=>$request->last_name,
'email'=>$request->email,
'password'=> Hash::make($request->password)
]);
return response()->json([
'status'=>true,
'message'=>'User created successfully',
'token'=>$user->createToken("API TOKEN")->plainTextToken
],200);
}
catch (\Throwable $th){
return response()->json([
'status'=>false,
'message'=>$th->getMessage()
],500);
}
}
}
and i got problem when i send post request json
like
{
"status": false,
"message": "SQLSTATE[42P01]: Undefined table: 7 ERROR: relation \"users\" does not exist\nLINE 1: select count(*) as aggregate from \"users\" where \"email\" = $1\n ^ (SQL: select count(*) as aggregate from \"users\" where \"email\" = something#abc.com)"
}
please help me
Instead of:❌
'email'=>'required|email|unique:users,email',
Use this:✅
'email'=>'required|email|unique:user,email',
Note the table name defined in your User Model is user.
Hence, that has to be reflected in your validation rules as well.
You forget to check you table in in validation
'email'=>'required|email|unique:users,email',
replace users to user
You are using the wrong table name in the validation, you need to replace 'users' by 'user' :
'email'=>'required|email|unique:users,email' to be 'email'=>'required|email|unique:user,email'

How to save entities across two databases in Laravel (Backpack)

I am new with Laravel and of course also with backpack.
I am using laravel 7.x and backpack 4.1 with both MySql and MongoDb.
The situation I am facing is that I have a company model with some attributes which are in MySql (both save and update working great with for the attributes stored in MySql) and other attributes that should be stored in MongoDb.
I have a CompanyPropertyCollection model for the attributes which I want to be stored in MongoDb
All these company will have a variable number of other arbitrary properties, which I want to save in mongo.
These properties may be simple scalar values or more complex values too (think arrays of objects), hence the idea to save them in mongo.
MySql Company table:
My question is the following:
What is the best practice to save attributes of an entity in two distinct databases from BackPack? I override the CreateOperation, UpdateOperation with the store() and update() functions something like this:
Company model:
class Company extends Model
{
use \Backpack\CRUD\app\Models\Traits\CrudTrait;
use SoftDeletes;
use HybridRelations;
protected $connection = 'mysql';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'company_type',
'is_active',
'package_id',
'certification_id',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'id' => 'integer',
'is_active' => 'boolean',
'package_id' => 'integer',
'certification_id' => 'integer',
];
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function users()
{
return $this->belongsToMany(\App\Models\User::class);
}
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function package()
{
return $this->belongsTo(\App\Models\Package::class);
}
public function certification()
{
return $this->hasMany(\App\Models\Certification::class);
}
public function properties()
{
return $this->hasOne(\App\Models\CompanyPropertyCollection::class);
}
}
CompanyPropertyCollection model:
class CompanyPropertyCollection extends Model
{
use SoftDeletes;
protected $connection = 'mongodb';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
//'company_id',
'email',
'big_news_id',
'phone.number',
'phone.country_prefix',
'phone.area_prefix',
'phone.postfix',
'year_of_foundation',
'nr_of_employees',
'nr_of_branches',
'company_size',
'subtitle',
'homepage',
'country_code',
'city',
'street',
'post_code',
'uid_nr',
'registration_nr',
'total_sales_area',
'total_annual_bisuness_volume',
'short_portrait',
'long_portrait',
'embedded_video',
'certificates',
'gallery',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'id' => 'integer',
'gallery' => 'array',
];
public function company()
{
return $this->belongsTo(\App\Models\Company::class);
}
}
CompanyCrudController :
public function update()
{
//$this->update( $company->properties);
$response = $this->traitUpdate();
// do something after save
//use registered observer
return $response;
}
Currently I am trying to use a CompanyObserver and on saving to store the data for mongo from the Request.
class CompanyObserver {
public function saving(Company $company)
{
//dd(request()->request);
$request = request()->request;
dd($company->properties());
//save to MongoDb
dd('saving methond on the observer');
}
}
If you need to perform some action after saving a model, like saving some user data in another db with a different type. You can override the model's save method.
Inside your model, add a method like the below
public function save(array $options = array())
{
if (parent::save($options)) {
// Model has been saved in mysql, now save in mongoDB
}
}

Laravel: Why Laravel accessor not work getIsVerifiedAttribute()?

I need to check the email of my users. So I add a new attribute to my User model named "is_verified" that returns me a boolean to know if the user has checked the email or not.
I running on PHP 7.2.5 with PHPUnit 7.5.15 and Laravel 5.8
model: User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Str;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'email', 'password', 'token', 'email_verified_at'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Retrive if user as vierfied
*
* #return boolean
*/
public function getIsVerifiedAttribute()
{
// dump(!is_null($this->email_verfied_at));
return !is_null($this->email_verfied_at);
}
/**
* Set if user is verified
*
* #param boolean $status
* #return void
*/
public function setIsVerifiedAttribute(bool $value)
{
if ($value) {
$this->attributes['token'] = null;
$this->attributes['email_verified_at'] = now();
} else {
$this->attributes['token'] = self::generateToken();
$this->attributes['email_verified_at'] = null;
}
}
/**
* Generate token to verify email
*
* #param integer $length
* #return string
*/
public static function generateToken(int $length = 64): string
{
$token = Str::random($length);
if (self::where('token', $token)->exists())
{
return self::generateToken($length);
}
return $token;
}
}
My unit test:
/** #test */
public function check_if_user_as_validate_email()
{
$user = factory(User::class)->create();
$this->assertFalse($user->is_verified);
$user->is_verified = true;
$user->save();
$this->assertTrue($user->is_verified);
$user->is_verified = false;
$user->save();
$this->assertFalse($user->is_verified);
}
The functions do not return me the good value every time
The reason your test isn't working is because you have a typo in your getIsVerifiedAttribute accessor. email_verfied_at should be email_verified_at.
public function getIsVerifiedAttribute()
{
return !is_null($this->email_verified_at);
}
Out-of-the-box, the User factory sets the email_verified_at field for you so I would suggest you change the code in your test for creating a User to:
$user = factory(User::class)->create([
'email_verified_at' => null
]);
This next bit is just an FYI but there are already methods included in with Laravel to check if a User is verified or not and to set the email_verified_at value:
$user->hasVerifiedEmail();
and
$user->markEmailAsVerified();

Relationships with Laravel

I do not know why, but the result that I am getting it's empty... I am trying to make a relation between a supervisor and a branc_office.
The branch_office just has one supervisor.
The supervisors can have many branch_office to manage.
So the relation it's 1 to Many.
My tables are:
Branch_office fields:
id_branch_office
id_supervisor
branch_office
User fields:
id_user
name
The id_supervisor and id_user make the relation between them.
id_supervisor(foreign key) ----- id_user(primary key)
My models:
User.php
use Notifiable;
protected $primaryKey = 'id_user';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'full_name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* Get the comments for the blog post.
*/
public function branch_offices()
{
return $this->hasMany('App\Branch_Office', 'id_supervisor');
}
Branch_office.php
protected $table = 'branch_offices';
protected $primaryKey = 'id_branch_office';
/**
* Get the post that owns the comment.
*/
public function supervisor()
{
return $this->belongsTo('App\User', 'id_user');
}
In the controller I am doing this:
$branch_office_detail = Branch_Office::find(1)->supervisor()->first();
but it displays a null or empty result... and there is a branch_office with id = 1
So I wonder, what it's wrong? becaiuse I have done this step by step and It's not working.
Thanks.
protected $table = 'branch_offices';
protected $primaryKey = 'id_branch_office';
public function supervisor()
{
return $this->belongsTo('App\User', 'id_supervisor', 'id_user');
}
In almost all relationships the first param is the model, the second the foreign key, the third the local key. Also the the belongsTo function only return one record or null, you dont need to use first()
BranchOffice::find(1) returns the Branch;
BranchOffice::find(1)->supervisor returns the supervisor of the branch 1
BranchOffice::with('supervisor')->find(1) return the office with the supervisor

NeoEloquent Class not found Symfony\Component\Debug\Exception\FatalThrowableError

I'm trying to create a link in between 2 objects using NeoEloquent. Unfortunately i get the following error.
Class 'Permission' not found
I tried pretty much everything but i can't get it to work unfortunately.
I submit the permission objects I want to link to as an integer representing the id of the label.
The relationship between the labels is a Many to Many relation. As far as i can see i've done everything correctly. I've checked with the GitHub page, it looks good to me.
Thanks in advance!
Controller method:
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param Role $role
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Role $role)
{
//dd($request);
$this->validate($request, [
'title' => 'required',
]);
foreach($request['permission'] as $perm){
$role->permissions()->attach($perm);
}
$role->title = request('title');
$role->save();
return redirect("/roles");
}
Role Model:
<?php
namespace App;
use Vinelab\NeoEloquent\Eloquent\Model as NeoEloquent;
class Role extends NeoEloquent
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'title',
];
protected $label = "Role";
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
];
public function permissions(){
return $this->hasMany('Permission', 'Has_Permission');
}
}
Permission Model:
<?php
namespace App;
use Vinelab\NeoEloquent\Eloquent\Model as NeoEloquent;
class Permission extends NeoEloquent
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'title',
];
protected $label = "Permission";
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
];
}

Categories