I am using databaseeder to store the name of controller in the permissions table but i didnot why i am getting error.This table have a relation with roles table using belongsToMany relation.
Here is my Role.php
public function permissions()
{
return $this->belongsToMany(Permission::class)->withTimeStamps();
}
Here is my Permission.php
protected $fillable=['id','name','controller'];
public function roles()
{
return $this->belongsToMany(Role::class)->withTimeStamps();
}
And Here is my databaseSeeder.php
$superrole= Role::create([
'name'=>'super admin',
]);
$permission_ids = [];
$route_name = [];
$controllers = [];
foreach (Route::getRoutes()->getRoutes() as $route)
{
$action = $route->getAction();
if (array_key_exists('as', $action)) {
$route_name = $action['as'];
}
if (array_key_exists('uses', $action)) {
$controllers = $action['uses'];
}
$permission_check = Permission::whereIn('name' , $route_name)
->whereIn('controller' , $controllers)->first();
if(!$permission_check)
{
$permission = new Permission;
$permission->controller = $controllers;
$permission->name = $route_name;
$permission->save();
$permission_ids[] = $permission->id;
}
}
$superrole->permissions()->attach($permission_ids);
But when i try to run the db:seed iam getting this error]1
Here is the dd($controllers)
and dd($route_name)
Related
I am a newbie in Laravel. So I am trying to update my form but it kept returning fail because I used the findOrFail method on the Controller.
But when I tried to dump the Id, the Id does exists.
Only when I call it using the method, it returns null.
Route for update
Route::post('/alumni/updateProfile','AlumniController#update');
Update method
public function update(Request $request, User $user, Profile $profile)
{
$user->roles()->sync($request->roles);
$profile = Profile::findOrFail(Auth::user()->id);
$profile->name = $request->name;
$profile->matric_no = $request->matric_no;
$profile->contact_no = $request->contact_no;
$profile->address = $request->address;
$profile->batch_year = $request->batch_year;
$profile->graduation_year = $request->graduation_year;
$profile->date_of_birth = $request->date_of_birth;
$profile->area_of_interest = $request->area_of_interest;
$profile->start_date = $request->start_date;
$profile->company_name = $request->company_name;
$profile->job_title = $request->job_title;
$profile->social_network = $request->social_network;
$profile->save();
return view('/home', compact('profile'));
}
Profile model
class Profile extends Model
{
// protected $guarded = [];
protected $fillable = ['alumni_id'];
protected $table = 'profiles';
public $timestamps = false;
public function users()
{
return $this->belongsTo('App\User');
}
}
User model
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function roles()
{
return $this->belongsToMany('App\Role');
}
public function profiles()
{
return $this->belongsTo('App\Profile');
}
public function hasAnyRoles($roles)
{
if($this->roles()->whereIn('name', $roles)->first()){
return true;
}
return false;
}
public function hasRole($role)
{
if($this->roles()->where('name', $role)->first()) {
return true;
}
return false;
}
Glad if any of you noticed anything, thank you.
You can write findOrFail() in try catch blog and get the exception in catch blog to understand the error.
OR
you can write below code instead of findOrFail().
$profile = Profile::where('id', '=', Auth::user()->id);
if( $profile->count() ){
# Assignment of values to database columns fields and then save.
$profile->save();
} else {
# Print No Record Found.
}
there.
So, I'm making a section for My reports, and I need to get the reports, from the database, based on id of logged user. How can I make that in my controller? I'm using \App\Reports::get(), but I need to get it based on the id of logging user, which is saved in database at user_id.
public function myReports($page = null)
{
if ($user = Sentinel::check())
{
// return $user;
$data = $this->data;
$id = $user->id;
$data['title'] = "My Reports";
$reports = \App\Reports::get();
$data['leftside_profile'] = 'my-reports';
$find_contact[] = $id;
// DB::enableQueryLog();
$page = Input::get('page');
$perPage = 10;
$offset = ($page * $perPage) - $perPage;
{
$query->whereIn('user_id',$find_contact)
->where('type', '=', 'profile_updates');
});
return view('profile.my_reports',$data)
->with(compact('reports'));
}
else{
return redirect('home');
}
}
Reports model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Reports extends Model
{
protected $table = 'reports';
// public $timestamps = false;
protected $fillable = [
'user_id', 'username', 'user_id_posted', 'username_posted', 'news_id','opinion_id','event_id','career_solution_id', 'subject', 'why_reporting','why_reporting_message','additional_message','private'
];
public function career_solutionReport()
{
return $this->belongsTo('App\CareerSolution','career_solution_id','id');
}
public function eventReport()
{
return $this->belongsTo('App\Event','event_id','id');
}
public function newsReport()
{
return $this->belongsTo('App\News','news_id','id');
}
public function opinionReport()
{
return $this->belongsTo('App\Opinion','opinion_id','id');
}
public function user()
{
return $this->belongsTo('App\User','user_id','id');
}
}
If the user is logged in you can call Sentinel::getUser()->id to retrieve the user id.
Change
$reports = \App\Reports::get();
To
$reports = \App\Reports::where('user_id', Sentinel::getUser()->id)->get();
I'm using Lumen, trying to edit values, which is the easiest thing to do, for some reason, the updated values aren't being saved
Task.php model
public function taskUsers()
{
return $this->hasMany('App\Models\Tasks\UserTask')->where('role',1);
}
UserTask.php model contains nothing, an empty model
class UserTask extends BaseModel { }
Migrations
class CreateTasksTable extends Migration
{
protected $table = 'tasks';
protected $app_table = true;
public function up()
{
Schema::create($this->getTable(), function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->dateTime('submit_date');
$table->dateTime('closed_date')->nullable();
$table->dateTime('due_date')->nullable();
$table->tinyInteger('is_done')->nullable()->default(0);
$table->integer('domain_id')->unsigned()->nullable();
$table->foreign('domain_id')->references('id')
->on(self::getTableName('domains'))->onDelete('cascade');
$table->bigInteger('created_by')->unsigned()->nullable();
$table->foreign('created_by')->references('id')
->on(self::getTableName('auth_users', false))->onDelete('cascade');
$table->bigInteger('closed_by')->unsigned()->nullable();
$table->foreign('closed_by')->references('id')
->on(self::getTableName('auth_users', false))->onDelete('cascade');
$table->timestamps();
});
}
public function down()
{
Schema::drop($this->getTable());
}
}
and
class CreateTaskUsersTable extends Migration
{
protected $table = 'task_user';
protected $app_table = true;
public function up()
{
Schema::create($this->getTable(), function (Blueprint $table) {
$table->increments('id');
$table->integer('task_id')->unsigned()->nullable();
$table->foreign('task_id')->references('id')
->on(self::getTableName('tasks'))
->onDelete('cascade');
$table->bigInteger('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')
->on(self::getTableName('auth_users', false))
->onDelete('cascade');
$table->integer('role');
});
}
public function down()
{
Schema::drop($this->getTable());
}
}
The edit action for example is so simple, if I just want to edit the title, that won't work, without even editing the rest.
class EditTaskAction extends BaseAction
{
protected $verbs = array('POST');
protected $private = true;
protected $inputRules = [
'domain_id' => 'required',
'task_id' => 'required',
'title' => '',
'due_date' => '',
'assignee_id' => '',
'is_done' => '',
'role' => ''
];
public function execute()
{
$title = $this->request->get('title');
$dueDate = $this->request->get('due_date');
$assigneeId = $this->request->get('assignee_id');
$taskId = $this->request->get('task_id');
$isDone = $this->request->get('is_done');
$role = $this->request->get('role');
$userId = \Auth::id();
$domainId = $this->request->get('domain_id');
\DB::beginTransaction();
try {
$task = Task::where('id', $taskId)
->where("domain_id", $domainId) ->first();
$userTask = UserTask::where('task_id', $taskId)->first();
if (isset($title) && !empty($title)) {
$task->title = $title;
}
if (isset($dueDate) && !empty($dueDate)) {
$task->due_date = $dueDate;
}
if (isset($assigneeId) && !empty($assigneeId)) {
$userTask->user_id = $userId;
}
if (isset($role) && !empty($role)) {
if ($role == TaskUserRole::ASSIGNEE) {
$userTask->role = $role;
}
}
if (isset($isDone) && !empty($isDone) ) {
if ($isDone == 0) {
$task->closed_by = null;
$task->closed_date = null;
$task->is_done = 0;
} else if ($isDone == 1) {
$task->closed_by = $userId;
$task->closed_date = Carbon::now();
$task->is_done = 1;
}
}
$task->save();
$userTask->save();
return $this->response->statusOk();
} catch (\Exception $exception) {
\DB::rollBack();
\Log::error($exception);
$this->response->addErrorDialog(self::SOMETHING_WENT_WRONG);
return $this->response->statusFail(self::SOMETHING_WENT_WRONG);
}
\DB::commit();
}
}
Basically all I'm doing
$task = Task::find($taskId); // I tried that too
$task->title = 'something';
$task->save();
It's not working
I think the problem is with your transaction. You're starting it with \DB::beginTransaction(); But the \DB::commit() (to save your changes to the database) will never be run, because you do Return-Statements before, like return $this->response->statusOk();
You could try to save your response to a variable and return it after the \DB::commit();
class EditTaskAction extends BaseAction
{
// ...
public function execute()
{
// ...
$response = null;
\DB::beginTransaction();
try {
// ...
$task->save();
$userTask->save();
$response = $this->response->statusOk();
} catch (\Exception $exception) {
// ...
$response = $this->response->statusFail(self::SOMETHING_WENT_WRONG);
}
\DB::commit();
return $response;
}
}
i thinks the problem in your model do you put your data stored in fillable
Did you set the guarded property on the model? You can completely disable guarding by setting it to an empty array.
protected $guarded = [];
// or check this:
protected $fillable = [...];
Otherwise you might find some error in the logs.
I have a many to many relation between the tables user and clinic and the third table is user_clinics. All three tables returns their values perfectly individually, but when i call App\User::find(1)->clinics or its inverse it returns null. Moreover, user_clinic has user_id and clinic_id and also previlage_id as a foreign key.
public function users() {
return $this->belongsToMany(User::class,'user_clinics','user_id','clinic_id');
}
public function clinics() {
return $this->belongsToMany(Clinic::class,'user_clinics','clinic_id','user_id');
}
public function adminDashboard(Request $request) {
$clinic = new Clinic();
$User_clinic = new User_clinic();
$user = new User();
$clinic->name = $request->name;
$clinic->address = $request->address;
if($request->hasFile('logo')) {
$fileName = $request->logo->getClientOriginalName();
$request->logo->storeAs('public/logos',$fileName);
$clinic->logo = $request->logo;
}
$clinic->save();
$User_clinic->user_id = auth::user()->id;
$test=$User_clinic->clinic_id = $clinic->id;
//now hardcoded previlage_id but deal with it in future...
$User_clinic->previlage_id = 1;
$User_clinic->save();
$test= $clinic::find(2)->users;
dd($test);
//return view("admin.dashboard.dashboardFirstPage");
}
Your relationship is not quiet right:
public function users() {
return $this->belongsToMany(User::class,'user_clinics','user_id','clinic_id');
}
public function clinics() {
return $this->belongsToMany(Clinic::class,'user_clinics','clinic_id','user_id');
}
It should be like below:
In User model:
public function clinics() {
return $this->belongsToMany(Clinic::class,'user_clinics','user_id','clinic_id');
}
In Clinic model:
public function users() {
return $this->belongsToMany(User::class,'user_clinics','clinic_id','user_id');
}
I am using this Controller to get permission to users to there projects
public function show($id)
{
if (Permission::where('status', 1)->where('project_id', $id)->exists()) {
// if((Permission::where('status', '=', '1')->first()) && (Permission::where('project_id','=',$id)->first())){
$project = Project::find($id);
$tasks = $this->getTasks($id);
$files = $this->getFiles($id);
$comments = $this->getComments($id);
$collaborators = $this->getCollaborators($id);
$permissions = $this->getPermissions($id);
returnview('collaborators.show')->withProject($project)->withTasks($tasks)->withFiles($files)->withComments($comments)->withCollaborators($collaborators);
}
else if
//return('hi');
(Permission::where('status', 2)->where('project_id', $id)->exists()) {
$project = Project::find($id);
$tasks = $this->getTasks($id);
$files = $this->getFiles($id);
$comments = $this->getComments($id);
$collaborators = $this->getCollaborators($id);
$permissions = $this->getPermissions($id);
return view('collaborators.manager')->withProject($project)->withTasks($tasks)->withFiles($files)->withComments($comments)->withCollaborators($collaborators);
}
My permission model is
<?php
namespace App;
use Auth;
use Illuminate\Database\Eloquent\Model;
class Permission extends Model
{
protected $table = 'permissions';
protected $fillable = ['status','project_id','collaborator_id'];
public function scopeProject($query, $id)
{
return $query->where('project_id', $id);
}
public function scopeProjectp($query, $cid)
{
return $query->where('collaborator_id', $cid);
}
public function scopePermissioneditt($query, $id, $projectId)
{
return $query->where('collaborator_id',$id)->where('project_id',$projectId);//->exists();
}
public function scopeProjectac($query)
{
return $query->where('collaborator_id', Auth::user()->id);
}
/* public static function permission($collaboratorId, $projectId)
{
return Permission::where('collaborator_id', $collaboratorId)->where('project_id', $projectId);
}*/
public function user()
{
return $this->belongsTo(User::class, 'collaborator_id');
}
/* public function project()
{
return $this->belongsToMany('App\Project');
}*/
public function project_collaborator()
{
return $this->belongsToMany('App\Collaboration','collaborator_id');
}
//
}
I need check and access permission table according to current user Auth::user->id; to give permission users.