How is set different roles and add new role - php

Im using system where it is using $user->is_admin and $user->is_employee and $user->is_customer there is no column is_admin or is_employee or is_customer in database. I know that it takes it from user model. but is_admin or is_employee is not defined anywhere. and dumping gives me true or false.
I want add new checking like is_manager. but cant find where I can add this..
Debugbar isnt showing any query for is_admin column..
Where it can be located?
example I have observer:
use App\Helper\SearchLog;
use App\User;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
class UserObserver
{
public function roleAttached(User $user, $role, $team)
{
if (!$user->is_admin) {
$type = 'Employee';
$route = 'admin.employee.edit';
if ($user->is_customer) {
$type = 'Customer';
$route = 'admin.customers.show';
}
SearchLog::createSearchEntry($user->id, $type, $user->name, $route);
SearchLog::createSearchEntry($user->id, $type, $user->email, $route);
}
}
I dont understand how it knows is_admin if it is not in database column?
My user model:
namespace App;
use App\Observers\UserObserver;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laratrust\Traits\LaratrustUserTrait;
class User extends Authenticatable
{
//------------------------------------ Traits ---------------------------
use LaratrustUserTrait;
use Notifiable;
//------------------------------------ Attributes ---------------------------
protected static function boot() {
parent::boot();
static::observe(UserObserver::class);
static::laratrustObserve(UserObserver::class);
}
/**
* 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',
];
protected $appends = [
'user_image_url', 'mobile_with_code', 'formatted_mobile'
];
/**
* The attributes that should be mutated to dates.
*
* #var array
*/
protected $dates = ['deleted_at'];
//------------------------------------ Relations ----------------------------
public function employeeGroup() {
return $this->belongsTo(EmployeeGroup::class, 'group_id');
}
public function todoItems() {
return $this->hasMany(TodoItem::class);
}
public function completedBookings() {
return $this->hasMany(Booking::class, 'user_id')->where('bookings.status', 'completed');
}
public function booking() {
return $this->belongsToMany(Booking::class);
}
public function services() {
return $this->belongsToMany(BusinessService::class);
}
public function leave()
{
return $this->hasMany('App\Leave', 'employee_id', 'id');
}
public function role()
{
return $this->belongsToMany(Role::class);
}
public function employeeSchedule()
{
return $this->hasMany('App\EmployeeSchedules', 'employee_id', 'id');
}
//------------------------------------ Scopes -------------------------------
public function scopeAllAdministrators() {
return $this->whereHas('roles', function ($query) {
$query->where('name', 'administrator');
});
}
public function scopeAllCustomers() {
return $this->whereHas('roles', function ($query) {
$query->where('name', 'customer')->withoutGlobalScopes();
});
}
public function scopeOtherThanCustomers() {
return $this->whereHas('roles', function ($query) {
$query->where('name', '<>', 'customer');
});
}
public function scopeAllEmployees() {
return $this->whereHas('roles', function ($query) {
$query->where('name', 'employee');
});
}
//------------------------------------ Accessors ----------------------------
public function getUserImageUrlAttribute() {
if (is_null($this->image)) {
return asset('img/default-avatar-user.png');
}
return asset_url('avatar/' . $this->image);
}
public function getRoleAttribute() {
return $this->roles->first();
}
public function getMobileWithCodeAttribute() {
return substr($this->calling_code, 1).$this->mobile;
}
public function getFormattedMobileAttribute() {
if (!$this->calling_code) {
return $this->mobile;
}
return $this->calling_code.'-'.$this->mobile;
}
public function routeNotificationForNexmo($notification) {
return $this->mobile_with_code;
}
public function getIsAdminAttribute() {
return $this->hasRole('administrator');
}
public function getIsEmployeeAttribute() {
return $this->hasRole('employee');
}
public function getIsCustomerAttribute() {
if ($this->roles()->withoutGlobalScopes()->where('roles.name', 'customer')->count() > 0) {
return true;
}
return false;
}
//------------------------------------ Mutators -----------------------------
public function setPasswordAttribute($value) {
$this->attributes['password'] = bcrypt($value);
}
//------------------------------------ Formats -----------------------------
public function userBookingCount($date) {
return Booking::whereNull('deal_id')->where('user_id', $this->id)->whereDate('created_at', $date)->get()->count();
}
} /* end of class */
LoginController looks like this where is authenticated class:
protected function authenticated(Request $request, $user)
{
if ($user->is_admin || $user->is_employee) {
return redirect()->route('admin.dashboard');
}
if(!$user->is_admin && !$user->is_employee && Cookie::get('bookingDetails')!==null && Cookie::get('products')!==null && $this->checkUserBooking($user->id)>$this->settings->booking_per_day){
return redirect(route('front.index'))->withCookie(Cookie::forget('bookingDetails'))->withCookie(Cookie::forget('products'))->withCookie(Cookie::forget('couponData'));
}
return redirect(session()->get('url.encoded'));
}

You can make another accessor that will check if role is associated with current user entity.
public function getIsManagerAttribute() {
return $this->hasRole('manager');// presuming you have created manager role
}
Then you can check easily with
// $user = User::find(1);
// $user->is_manager;// true || false

Related

How to retrieve and display relationship data in Laravel?

I have three tables in the database. orders, products, and order_product table. this is how they look like in my phpmyAdmin https://imgur.com/a/Ud9e2Hh
I would like sellers to see orders placed by buyers in their view (dashboard). Also, buyers to be able to see their orders in their view.
Here are my relationships in models
User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
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', 'Seller'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
//public function isSeller() {
// return $this->seller;
//}
public function products()
{
return $this->hasMany(Products_model::class);
}
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function orders()
{
return $this->hasManyThrough(Order::class, Products_model::class, 'buyer_id', 'seller_id', 'product_id');
}
public function orderFromBuyers()
{
return $this->hasManyThrough(OrderProduct::class, Products_model::class, 'buyer_id', 'product_id');
}
public function orderFromSellers()
{
return $this->hasManyThrough(OrderProduct::class, Products_model::class, 'seller_id', 'product_id');
}
}
OrderProduct.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class OrderProduct extends Model
{
protected $table = 'order_product';
protected $fillable = ['order_id', 'buyer_id', 'seller_id','product_id', 'quantity'];
public function products()
{
return $this->belongsTo('App\Products_model');
}
public function buyer()
{
return $this->belongsTo(User::class, 'id', 'buyer_id');
}
public function seller()
{
return $this->belongsTo(User::class, 'id', 'seller_id');
}
public function order()
{
return $this->belongsTo(Order::class);
}
}
Order.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
//protected $table = 'orders';
protected $fillable = [
'shipping_email', 'shipping_name', 'shipping_city', 'shipping_phone', 'billing_subtotal', 'billing_total',
];
public function user()
{
return $this->belongsTo('App\User');
}
public function products()
{
return $this->belongsToMany('App\Products_model')->withPivot('quantity');
}
public function orders()
{
return $this->hasMany('App\OrderProduct', 'order_id');
}
}
Seller Function
// Seller Orders
public function viewOrders(User $user)
{
// $products = Products_model::where('seller_id', '=', $user->id)->get();
// all sells
$sells = $user->orderFromSellers();
dd($sells);
return view('orders')->with(compact('sells'));
}
Buyer Function
//Buyer Orders
public function myOrders()
{
$cart = session();
$orders = Auth::user()->orders;
$orders->transform(function($order, $key) {
dd($orders);
$order->cart = unserialize($order->cart);
return $order;
});
return view('myOrders', ['orders' => $orders]);
}
Right now it shows nothing. Any help on how to solve this will be appreciated.
Products_model
protected $table='products';
protected $primaryKey='id';
protected $fillable=['seller_id','pro_name','pro_price','pro_info','image','stock','category_id '];
Try by changing two function.
public function orderFromBuyers()
{
return $this->hasManyThrough(Products_model::class, OrderProduct::class, 'buyer_id', 'product_id');
}
public function orderFromSellers()
{
return $this->hasManyThrough(Products_model::class, OrderProduct::class, 'seller_id', 'product_id');
}
Or the two will be more better. Add these two functions to User model.
public function allOrderFromBuyers()
{
return $this->hasMany(OrderProduct::class, 'buyer_id');
}
public function allOrderFromSellers()
{
return $this->hasMany(OrderProduct::class, 'seller_id');
}
Then change this to,
// Seller Orders
public function viewOrders(User $user)
{
// all sells
$sells = $user->allOrderFromSellers();
dd($sells);
return view('orders')->with(compact('sells'));
}

Insert into many to many relation table in Laravel

In my laravel project, I have tables that i want to insert a many to many relationship between 2 of them. I want to bind an User(that must be a cleaner kind) to one House of many from current Host user authenticated. To do so, I'm implementing the following function in Controller:
public function hireCleanerToHouse (Request $request)
{
$house_id = $request->houseAssign;
$email = $request->email;
$house = House::find($house_id);
$cleanerUser = User::where('email', $email)->first();
if ($cleanerUser && $house){
$cleanerUser->houses()->attach($house);
}
return response()->json('success', 200);
}
May I am missing a detail of logic that cant let me insert any data. Im pretty new using laravel and the Eloquent ORM.
to help understand better, here are the Models from project. The functions that take care of a separates tables (CRUD) are all working fine.
If there are some other tip to improve legibity or if I'm ignoring some best pratice, I will gladly accept it.
User:
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 host()
{
return $this->hasOne(Host::class);
}
public function cleaner()
{
return $this->hasOne(Cleaner::class);
}
}
House:
class House extends Model
{
protected $fillable = ['name', 'address', 'host_id'];
protected $dates = ['created_at', 'updated_at'];
protected $appends = ['next_cleaning'];
public function host()
{
return $this->belongsTo(Host::class);
}
public function cleaners()
{
return $this->belongsToMany(
Cleaner::class,
'cleaners_houses',
'house_id',
'cleaner_id'
);
}
public function cleanings()
{
return $this->hasMany(CleaningProject::class);
}
public function getNextCleaningAttribute()
{
return $this->cleanings()->orderBy('created_at', 'desc')->first();
}
}
Cleaner:
class Cleaner extends Model
{
protected $dates = ['created_at', 'updated_at'];
public function houses()
{
return $this->belongsToMany(
House::class,
'cleaners_houses',
'cleaner_id',
'house_id'
);
}
public function hosts()
{
return $this->belongsToMany(
Host::class,
'cleaners_hosts',
'cleaner_id',
'host_id'
);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function cleanings()
{
return $this->hasMany(CleaningProject::class);
}
public function getNameAttribute()
{
return $this->user->name;
}
}
Host
class Host extends Model
{
protected $dates = ['created_at', 'updated_at'];
protected $appends = ['name'];
public function houses()
{
return $this->hasMany(House::class);
}
public function cleaners()
{
return $this->belongsToMany(
Cleaner::class,
'cleaners_hosts',
'host_id',
'cleaner_id'
);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function getNameAttribute()
{
return $this->user->name;
}
}
And also the migration that bind many Cleaners to many House is already created:
Migration
class CreateCleanersHousesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('cleaners_houses', function (Blueprint $table) {
$table->increments('id');
$table->integer('cleaner_id')->references('id')->on('cleaners');
$table->integer('house_id')->references('id')->on('houses');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('cleaners_houses');
}
}
here's the solution that I found:
public function hireCleanerToHouse (Request $request)
{
$email = $request->email;
$houseId = $request->idHouse;
$idUserEmail = User::where('email', $email)->first();
$cleaner = Cleaner::where('user_id', $idUserEmail->id)->first();
$house = House::find($houseId);
$cleaner->houses()->attach($house->id);
return response()->json([$cleaner, $house], 200);
}
As you may see the problemn was because the model Cleaner only contains 'id' and 'user_id', so i had to get first the user.id and find the cleaner where user_id = user.id.
Also I don't passed the $house->id in the attach() to match the relationship. Its now working fine. hope it helps someone else.

SQLSTATE[HY000]: General error: 1364 Field 'accepted' doesn't have a default value

Hello I am attempting to create a friend system somewhat like the Facebook where you can add another user as a friend however, once I click the button add friend it gives me this error. Any help will be very much appreciated thank you.
SQLSTATE[HY000]: General error: 1364 Field 'accepted' doesn't have a
default value (SQL: insert into friends (friend_id, user_id)
values (1, 3))
User.php
<?php
namespace Kermode;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name','last_name', 'email', 'password','gender',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function getName()
{
if ($this->first_name && $this->last_name) {
return "{$this->first_name} {$this->last_name}";
}
if ($this->first_name) {
return $this->first_name;
}
return null;
}
public function getNameOrUsername()
{
return $this->getName() ?: $this->username;
}
public function getFirstNameOrUsername()
{
return $this->first_name ?: $this->username;
}
public function getAvatarUrl()
{
return "https://www.gravatar.com/avatar/{{ md5($this->email) }}
?d=mm&s=40";
}
public function friendsOfMine()
{
return $this->belongsToMany('Kermode\User', 'friends', 'user_id',
'friend_id');
}
public function friendOf()
{
return $this->belongsToMany('Kermode\User' , 'friends', 'friend_id'
, 'user_id');
}
public function friends()
{
return $this->friendsOfMine()->wherePivot('accepted', true)->get()->
merge($this->friendOf()->wherePivot('accepted', true)->get());
}
public function friendRequests()
{
return $this->friendsOfMine()->wherePivot('accepted', false)->get();
}
public function friendRequestsPending()
{
return $this->friendOf()->wherePivot('accepted', false)->get();
}
public function hasFriendRequestPending(User $user)
{
return (bool) $this->friendRequestsPending()->where('id', $user->id)->
count();
}
public function hasFriendRequestRecieved(User $user)
{
return (bool) $this->friendRequests()->where('id', $user->id)->count();
}
public function addFriend(User $user)
{
$this->friendOf()->attach($user->id);
}
public function acceptFriendRequest(User $user)
{
$this->friendRequests()->where('id', $user->id)->first()->pivot->
update([
'accepted' => true,
]);
}
public function isFriendsWith(User $user)
{
return (bool) $this->friends()->where('id', $user->id)->count();
}
}
FriendController.php
<?php
namespace Kermode\Http\Controllers;
use Auth;
use Kermode\User;
use Illuminate\Http\Request;
class FriendController extends Controller
{
public function getIndex()
{
$friends = Auth::user()->friends();
$requests = Auth::user()->friendRequests();
return view('friends.index')
->with('friends', $friends)
->with('requests', $requests);
}
public function getAdd($first_name)
{
$user = User::where('first_name', $first_name)->first();
if (!$user) {
return redirect()
->route('home')
->with('info', 'That user could not be found');
}
if (Auth::user()->hasFriendRequestPending($user) || $user->
hasFriendRequestPending(Auth::user())) {
return redirect()
->route('profile.index', ['first_name' => $user->first_name])
->with('info', 'Friend request already pending.');
}
if (Auth::user()->isFriendsWith($user)) {
return redirect()
->route('profile.index', ['first_name' => $user->firstname])
->with('info', 'You are already friends');
}
Auth::user()->addFriend($user);
return redirect()
->route('profile.index', ['first_name' => $first_name])
->with('info', 'Friend request sent.');
}
}
profile.index.blade.php
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-leg-6">
<h3>Your friends</h3>
#if (!$friends->count())
<p>You have no friends</p>
#else
#foreach ($friends as $user)
#include('user/partials/userblock')
#endforeach
#endif
</div>
<div class="col-lg-6">
<h4>Friend Request</h4>
#if (!$requests->count())
<p>You have no friend requests.</p>
#else
#foreach ($requests as $user)
#include('user.partials.userblock')
#endforeach
#endif
</div>
</div>
#endsection
friendstable
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFriendsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('friends', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('friend_id');
$table->boolean('accepted');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('friends');
}
}
you have to add accepted
into $fillable
if you didnt add your column name into $fillable in your model, this error occurred
1364 Field 'accepted' doesn't have a default value
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['accepted'];
}
This error might be because of database. The accepted column needs to be nullable or have a default value like
$table->boolean('accepted')->nullable();
or
$table->boolean('accepted')->default(false);
Go and change your accepted column in your database data type to tinyint
then change as defined to 0 .. it will work one worked when I figured out this

Laravel repository store image name does not work

I'm trying to create a user profile and store it into database using laravel repositories .
below is my controller code :
<?php
namespace App\Http\Controllers;
use App\Http\Requests\UsercreateRequest;
use App\Http\Requests\UserupdateRequest;
use App\Repositories\UserRepository;
use Illuminate\Http\Request;
class UserController extends Controller
{
protected $userRepository;
protected $nbrPerPage=4;
public function __construct(UserRepository $UserRepository)
{
$this->userRepository=$UserRepository;
}
public function index()
{
return view('signup');
//
}
public function create()
{
return view('signup');
//
}
public function store(UsercreateRequest $request)
{
$image =$request->file('image');
if($request->hasFile('image'))
{
if($image->isValid())
{
$way=public_path('images');
$extension=$image->getClientOriginalExtension();
do
{
$name=$image->getClientOriginalName();
//echo $name;
}while(file_exists($way.'/'.$name));
if($image->move($way,$name))
{
echo'ok '; //75485205
//echo $name;
$user=$this->userRepository->store($request->all(), $request);
return redirect('dashboard')->withOk(" L'enrisgrement n'a pas abouti !");
}
}
}
return redirect('signup')->withOk(" L'enrisgrement n'a pas abouti !");
//
}
public function show($id)
{
$user=$this->userRepository->getByid($id);
return view('dashboard', compact('user'));
//
}
public function edit($id)
{
$user=$this->userRepository->getByid($id);
return view('dashboard', compact('user'));
//
}
public function update(UserupdateRequest $request, $id)
{
$this->userRepository->update($id, $request->all());
return view('dashboard');
//
}
public function destroy($id)
{
$this->userRepository->destroy($id);
return back();
//
}
}
The model is also as below
<?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','image',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
My repository
<?php
namespace App\Repositories;
use App\User;
use App\Http\Requests\UsercreateRequest;
class UserRepository{
protected $user;
public function __construc(User $user)
{
$this ->user=$user;
}
private function save (User $user, Array $inputs, UsercreateRequest $request)
{
$user->name=$inputs['name'];
$user->email=$inputs['email'];
$image=$request->file('image');
$name=$image->getClientOriginalName();
$user->image=$name;
$user->save();
}
public function store(Array $inputs,UsercreateRequest $request)
{
$user= new User();
$user->password=bcrypt($inputs['password']);
$this->save($user,$inputs,$request);
}
public function getByid ($id)
{
return $this->user->findOrfail($id);
}
public function update($id, Array $inputs)
{
$this->save($this->getByid($id),$inputs);
}
public function destroy ($id)
{
$this->getByid($id)->delete();
}
}
In my save function when i simply write $user->image=inputs['image'] it works but instead of the image name its store a path to my socket . how can i use getClientOriginalName() here to get the client image and store it in the database ?
any idea ?
Thanks
Change your store method call to this.
$data = array_merge($request->all(), ['image' => $name]);
$user = $this->userRepository->store($data, $request);
PS : The loop checking if the file already exists is useless. The loop will never end if an image with the same name as the uploaded file already exists.
do {
$name = $image->getClientOriginalName();
} while(file_exists($way.'/'.$name));
To fix this you should throw in some random name generator here.

Laravel comments and user relationship returns null

I'm trying to implement commenting system on my website but i'm having hard time with the relationships. for some reason when i try to access the user relation from the comment class it returns null.. my code:
Post.php
class Post extends Model
{
public $timestamps = false;
public $primaryKey = 'post_id';
protected $fillable = ['title','created_at','username','image'];
public function user()
{
return $this->belongsTo(User::class,'username');
}
public function votes()
{
//Quick note: Id refers to the post id.
return $this->hasMany(PostVotes::class,'post_id');
}
public function comments()
{
return $this->hasMany(Comment::class,'post_id');
}
}
User.php
class User extends Model implements Authenticatable
{
use AuthenticableTrait;
protected $primaryKey = 'username';
public $incrementing = false;
public $timestamps = false;
protected $fillable = ['username','email','password','created_at','avatar','about'];
// Gets avatar to display on navbar.
public function posts()
{
return $this->hasMany(Post::class,'username');
}
public function comments()
{
return $this->hasMany(Comment::class,'username');
}
public static function getAvatar()
{
return self::Where('username', '=', Session::get('username'))->value('avatar');
}
}
Comment.php
class Comment extends Model
{
public $timestamps = false;
public $primaryKey = 'post_id';
protected $fillable = ['comment','created_at','post_id','username'];
public function user()
{
$this->belongsTo(User::class,'username') ;
}
public function post()
{
$this->belongsTo(Post::class,'post_id');
}
}
public function view($post_id)
{
$post = Post::with('comments')->findOrFail($post_id);
return view('posts.view',compact('post'));
}
#foreach($post->comments as $comment)
// null
{{dd($comment->user())}}
#endforeach
Use missed the return keyword
public function user()
{
return $this->belongsTo(User::class,'username') ;
}
public function post()
{
return $this->belongsTo(Post::class,'post_id');
}
public function displaycomment($id) {
$data['comment'] = comment::select('comments.id', 'comments.description', 'users.name', 'comments.created_at', 'comments.post_id')->where('post_id',$id)->leftjoin('users', 'users.id', '=', 'comments.user_id')->get();
// dd($data);
return view('displayblog', compact('data'));
}

Categories