I have a case with several models. Order Model, Product Model, Port Model, and Logistic Model.
With an Order belongsTo Many Products, Order Belongs To Port with 'to_port_id' ,Order Belongs To Logistic with 'logistic_id', Product belongs To Port with 'from_port_id',
from_port_id , to_port_id ,logistic_id and unit_price combined with a pivot table .
And now I want to ask. How to retrieve an order with different products with corresponding from_port_id,to_port_id,logistic_id to get different unit_price with the eager load as little sql as possible?
Order Model
+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+----------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| to_port_id | int(11) | NO | | NULL | |
| logistic_id | int(11) | NO | | NULL | |
+--------------+-------------+------+-----+---------+----------------+
Product Model
+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+----------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| from_port_id | int(11) | NO | | NULL | |
+--------------+-------------+------+-----+---------+----------------+
LogisticPort PivotModel
+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+----------------+
| from_port_id | int(11) | NO | PRI | NULL | |
| to_port_id | int(11) | NO | PRI | NULL | |
| logistic_id | int(11) | NO | PRI | NULL | |
| unit_price | decimal(11) | NO | | NULL | |
+--------------+-------------+------+-----+---------+----------------+
----------update -------------------------
class Product extends Model
{
protected $table = 'product';
/*
|--------------------------------------------------------------------------
| RELATIONS
|--------------------------------------------------------------------------
*/
public function orderTransact(){
return $this->belongsToMany('App\Models\OrderTransact','order_transact_product','product_id','order_transact_id')->withPivot(['unique_order_product_id','order_quantity_in_log','order_product_status_id ','confirmed_delivery_date','expected_ETD','due_at','downpayment','deposit','total','feedback','created_at','updated_at','tracking_no','weight','logistic_cost'])->using('App\Models\OrderTransactProduct')->as('order_product');
}
public function orderProduct(){
return $this->hasMany('App\Models\OrderTransactProduct','product_id','id');
}
public function fromLogisticPort(){
return $this->belongsTo('App\Models\LogisticPort','from_port_id','id');
}
}
class LogisticPort extends Model
{
use HasFactory;
protected $table = 'logistic_port';
public function logisticFrom(){
return $this->belongsToMany('App\Models\Logistic','logistic_port_logistic','from_port_id','logistic_id')->withPivot(['to_port_id','courier_charges_unit'])->using('App\Models\LogisticPortLogistic');
}
public function logisticTo()
{
return $this->belongsToMany('App\Models\Logistic','logistic_port_logistic','to_port_id','logistic_id')->withPivot(['from_port_id','courier_charges_unit'])->using('App\Models\LogisticPortLogistic');
}
public function logisticPortFrom(){
return $this->belongsToMany('App\Models\LogisticPort','logistic_port_logistic','to_port_id','from_port_id')->withPivot(['logistic_id','courier_charges_unit'])->using('App\Models\LogisticPortLogistic');
}
public function logisticPortTo(){
return $this->belongsToMany('App\Models\LogisticPort','logistic_port_logistic','from_port_id','to_port_id')->withPivot(['logistic_id','courier_charges_unit'])->using('App\Models\LogisticPortLogistic');
}
public function toPivotLogisticPort(){
return $this->hasMany('App\Models\LogisticPortLogistic','to_port_id','id');
}
public function product(){
return $this->hasMany('App\Models\Product','from_port_id','id');
}
public function orderTransact(){
return $this->hasMany('App\Models\OrderTransact','from_port_id','id');
}
}
class Logistic extends Model
{
protected $table = 'logistic';
public function orderTransact(){
return $this->hasMany('App\Models\OrderTransact','order_transact_id','id');
}
public function logisticPortFrom(){
return $this->belongsToMany('App\Models\LogisticPort','logistic_port_logistic','logistic_id','from_port_id')->withPivot(['to_port_id','courier_charges_unit'])->using('App\Models\LogisticPortLogistic');
}
public function logisticPortTo(){
return $this->belongsToMany('App\Models\LogisticPort','logistic_port_logistic','logistic_id','to_port_id')->withPivot(['from_port_id','courier_charges_unit'])->using('App\Models\LogisticPortLogistic');
}
}
class OrderTransact extends Model
{
use HasFactory;
use SoftDeletes;
protected $table = 'order_transact';
/*
|--------------------------------------------------------------------------
| RELATIONS
|--------------------------------------------------------------------------
*/
public function logistic(){
return $this->belongsTo('App\Models\Logistic','logistic_id','id');
}
public function product(){
return $this->belongsToMany('App\Models\Product','order_transact_product','order_transact_id','product_id')->withPivot(['unique_order_product_id','order_quantity_in_log','order_product_status_id','confirmed_delivery_date','expected_ETD','due_at','downpayment','deposit','total','feedback','created_at','updated_at','tracking_no','weight','logistic_cost'])->using('App\Models\OrderTransactProduct')->as('order_product');
}
public function orderProduct(){
return $this->hasMany('App\Models\OrderTransactProduct','order_transact_id','id');
}
public function toLogisticPort(){
return $this->belongsTo('App\Models\LogisticPort','to_port_id','id');
}
}
Related
In Laravel 8 app with inertiajs/vuejs2/fortify I try to run user register method wih axios
request(I need to make register wih confirmation code) from vue component :
makeRegisterStep1() {
console.log('makeRegisterStep1 this.registerForm::')
console.log(this.registerForm)
Window.axios.post('/register', this.registerForm)
.then(resp => {
console.log('makeRegisterStep1 resp::')
console.log(resp)
...
})
.catch(
function (error) {
console.error(error)
}
)
}, // makeRegisterStep1() {
bUT i GOT ERROR
POST http://127.0.0.1:8000/register 500 (Internal Server Error)
AND i SEE IN LOG FILE :
[2021-12-28 10:18:51] local.ERROR: Laravel\Fortify\Http\Controllers\RegisteredUserController::store(): Argument #2 ($creator) must be of type Laravel\Fortify\Contracts\CreatesNewUsers, App\Actions\Fortify\CreateNewUser given, called in /mnt/_work_sdb8/wwwroot/lar/photographers/li/vendor/laravel/framework/src/Illuminate/Routing/Controller.php on line 54 {"exception":"[object] (TypeError(code: 0): Laravel\\Fortify\\Http\\Controllers\\RegisteredUserController::store(): Argument #2 ($creator) must be of type Laravel\\Fortify\\Contracts\\CreatesNewUsers, App\\Actions\\Fortify\\CreateNewUser given, called in /mnt/_work_sdb8/wwwroot/lar/photographers/li/vendor/laravel/framework/src/Illuminate/Routing/Controller.php on line 54 at /mnt/_work_sdb8/wwwroot/lar/photographers/li/vendor/laravel/fortify/src/Http/Controllers/RegisteredUserController.php:51)
[stacktrace]
#0 /mnt/_work_sdb8/wwwroot/lar/photographers/li/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): Laravel\\Fortify\\Http\\Controllers\\RegisteredUserController->store()
#1 /mnt/_work_sdb8/wwwroot/lar/photographers/li/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(45): Illuminate\\Routing\\Controller->callAction()
#2 /mnt/_work_sdb8/wwwroot/lar/photographers/li/vendor/laravel/framework/src/Illuminate/Routing/Route.php(262): Illuminate\\Routing\\ControllerDispatcher->dispatch()
I modified app/Providers/FortifyServiceProvider.php, but not Create user part :
<?php
namespace App\Providers;
use App\Actions\Fortify\CreateNewUser;
use App\Actions\Fortify\ResetUserPassword;
use App\Actions\Fortify\UpdateUserPassword;
use App\Actions\Fortify\UpdateUserProfileInformation;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\ValidationException;
use Laravel\Fortify\Fortify;
class FortifyServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
public function boot()
{
Fortify::loginView(function () {
return view('auth.login', [] );
});
Fortify::authenticateUsing(function (Request $request) {
$user = User::where('email', $request->email)->first();
$request = request();
if ($user && Hash::check($request->password, $user->password)) {
if ( $user->status === 'A') {
return $user;
}
else {
throw ValidationException::withMessages([
Fortify::username() => __("Your account is inactive"),
]);
}
}
});
Fortify::registerView(function () {
return view('auth.register', [] );
});
Fortify::createUsersUsing(CreateNewUser::class);
Fortify::updateUserProfileInformationUsing(UpdateUserProfileInformation::class);
Fortify::updateUserPasswordsUsing(UpdateUserPassword::class);
Fortify::resetUserPasswordsUsing(ResetUserPassword::class);
RateLimiter::for('login', function (Request $request) {
return Limit::perMinute(5)->by($request->email.$request->ip());
});
RateLimiter::for('two-factor', function (Request $request) {
return Limit::perMinute(5)->by($request->session()->get('login.id'));
});
}
}
hOW IT CAN BE FIXED ?
MODIFIED BLOCK :
No the pipeline is default,
and checking routes I see :
php artisan route:list
| Illuminate\Auth\Middleware\EnsureEmailIsVerified |
| | GET|HEAD | register | register | Laravel\Fortify\Http\Controllers\RegisteredUserController#create | web |
| | | | | | App\Http\Middleware\RedirectIfAuthenticated:web |
| | POST | register | generated::qWOIdxP9ML8fo3yR | Laravel\Fortify\Http\Controllers\RegisteredUserController#store | web |
| | | | | | App\Http\Middleware\RedirectIfAuthenticated:web |
| | GET|HEAD | test | test | App\Http\Controllers\HomeController#test | web |
| | DELETE | user | current-user.destroy | Laravel\Jetstream\Http\Controllers\Inertia\CurrentUserController#destroy | web |
| | | | | | App\Http\Middleware\Authenticate |
| | | | | | Illuminate\Auth\Middleware\EnsureEmailIsVerified |
| | GET|HEAD | user/confirm-password | password.confirm | Laravel\Fortify\Http\Controllers\ConfirmablePasswordController#show
Header of app/Models/User.php :
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Permission\Traits\HasPermissions;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
class User extends Authenticatable implements HasMedia //, MustVerifyEmail
{
use HasRoles;
use HasPermissions;
use HasFactory;
use Notifiable;
use TwoFactorAuthenticatable;
use InteractsWithMedia;
protected $fillable
= [
'name',
'email',
'status',
'password'
];
Originally that was laravel 8 admin starter kit based on bootstrap/jquery, without Fortify/Jetstream.
I installed Fortify manually with login service I need.
Also I use CreateNewUser class in my users seeder : :
app(CreateNewUser::class)->create([
'id' => 1,
'name' => 'Admin',
'email' => 'admin#site.com',
'password' => '11111111',
'status' => 'A',
], true, [PERMISSION_APP_ADMIN]);
What did I miss?
Thanks!
I am a beginner of laravel framework. I am now having problem in authentication in laravel 5.2. I tried but I can't find error.
Email and password is correct but it is redirecting to login page.
Here is my DB
+----+-------+-----------------+----------+-------+----------------+---------------------+---------------------+
| id | name | email | password | phone | remember_token | created_at | updated_at |
+----+-------+-----------------+----------+-------+----------------+---------------------+---------------------+
| 1 | Admin | admin#gmail.com | 111111 | | NULL | 2017-01-03 05:40:06 | 2017-01-03 05:40:06 |
+----+-------+-----------------+----------+-------+----------------+---------------------+---------------------+
Here is UserController
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
use DB;
class UserController extends Controller
{
public function index()
{
if( !Auth::check() ) {
return view('user/index');
} else {
return view('user/profile');
}
}
public function login(Request $request)
{
if( Auth::attempt( array(
"email" => "admin#gmail.com",
"password" => "111111",
) ) ) {
return redirect('user/profile');
} else {
return redirect('user/login');
}
}
}
In Database you need to store password in encrypted format.Auth::attempt() will convert the password into encrypted form and compare with the password in database.
During data insertion into the database you need to use
bcrypt($password);
I have two models: Term and Post.
The Term model represents both categories and tags.
A post can belong only to a category and it can have many tags (I use the same db table for categories and tags).
class Term extends Model
{
protected $table = 'mydb_terms';
public $timestamps = true;
public function getRouteKeyName() {
return 'slug';
}
public function posts(){
return $this -> hasMany('Post');
}
}
class Post extends Model
{
use SoftDeletes;
protected $table = 'mydb_posts';
public $timestamps = true;
public function category(){
return $this -> belongsTo('Term','mydb_posts_terms', 'post_id', 'term_id')
-> withPivot('order') -> withTimestamps() -> where('type','category');
}
public function tags(){
return $this -> hasMany('Term') -> where('type','tag');
}
}
In the CategoryController I have:
class CategoryController extends Controller
{
public function getPostsOfCategory($id)
{
$posts = Term::find($id)->posts->get();
}
public function getPostsOfAllCategories()
{
//
}
}
When I try to retrieve the posts of category event with slug event (in the db the category and one post in it exist, and also the corresponding row in mydb_posts_terms) I obtain
Trying to get property of non-object
EDIT
I tried both $posts = Term::find($id)->posts()->get(); by obtaining Call to a member function and $posts = Term::find($id)->posts; by obtaining the same Trying to get property of non-object.
In the db I have:
Table mydb_terms:
| id | name | slug | type | created_at | updated_at
| 1 | event | event | category | 2016-07-01 18:00:00| 2016-07-01 18:00:00
Table mydb_posts:
| id | title | content | created_at | updated_at
| 1 | A title | a content | 2016-07-04 17:20:12| 2016-07-04 17:20:12
Table mydb_posts_terms:
| post_id | term_id | order | created_at | updated_at
| 1 | 1 | 0 | 2016-07-06 14:13:43| 2016-07-06 14:13:43
I'm building an Employee Management system and The employee part works good but when i try to create for family members for an employee i have a problem.
I was hoping i can create a family member for an employee in such a way
localhost/mysite/employees/5/families/create
Here are my files
P.S - I have omitted some of the code which i thought was irrelevant. For example, there are more than 30 employee fields that i save. For this question i just displayed the FirstName
routes.php
Route::resource('employees', 'EmployeesController');
Route::resource('employees.families', 'FamiliesController');
EmployeesController.php
<?php
namespace App\Http\Controllers;
use Carbon\Carbon;
use App\Employee;
use Illuminate\Http\Request;
use DB;
use App\Http\Controllers\Controller;
class EmployeesController extends Controller
{
public function index()
{
//Stuff that works well on employees/index
}
public function create()
{
//Stuff that works well on employees/create
}
public function store(Request $request)
{
//Stuff that works well
}
public function show(Employee $employee)
{
$employee=Employee::find($EmployeeID);
return view('employees.show', compact('employee'));
}
public function edit($EmployeeID)
{
$employee=Employee::find($EmployeeID);
return view('employees.edit',compact('employee'));
}
public function update(Request $request, $EmployeeID)
{
//Stuff that works well on employees/edit
}
}
Employee.php (Model)
<?php
namespace App;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $primaryKey = 'EmployeeID';
protected $fillable=[
'Name'
];
public function families()
{
return $this->hasMany('App\Family');
}
}
FamilyController.php (For now i only posted the index and create methods)
<?php
namespace App\Http\Controllers;
use App\Employee;
use App\Family;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class FamiliesController extends Controller
{
public function index(Employee $employee)
{
return view('families.index', compact('employee'));
}
public function create(Employee $employee)
{
return view('families.create', compact('employee'));
}
}
Family.php (Model)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Family extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $primaryKey = 'FamilyID';
public function employees()
{
return $this->belongsTo('App\Employee');
}
}
Result from php artisan route:list
+--------+----------+------------------------------------------------+----------------------------+--------------------------------------------------+------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+----------+------------------------------------------------+----------------------------+--------------------------------------------------+------------+
| | GET|HEAD | employees | employees.index | App\Http\Controllers\EmployeesController#index | |
| | POST | employees | employees.store | App\Http\Controllers\EmployeesController#store | |
| | GET|HEAD | employees/create | employees.create | App\Http\Controllers\EmployeesController#create | |
| | PATCH | employees/{employees} | | App\Http\Controllers\EmployeesController#update | |
| | PUT | employees/{employees} | employees.update | App\Http\Controllers\EmployeesController#update | |
| | DELETE | employees/{employees} | employees.destroy | App\Http\Controllers\EmployeesController#destroy | |
| | GET|HEAD | employees/{employees} | employees.show | App\Http\Controllers\EmployeesController#show | |
| | GET|HEAD | employees/{employees}/edit | employees.edit | App\Http\Controllers\EmployeesController#edit | |
| | GET|HEAD | employees/{employees}/families | employees.families.index | App\Http\Controllers\FamiliesController#index | |
| | POST | employees/{employees}/families | employees.families.store | App\Http\Controllers\FamiliesController#store | |
| | GET|HEAD | employees/{employees}/families/create | employees.families.create | App\Http\Controllers\FamiliesController#create | |
| | PUT | employees/{employees}/families/{families} | employees.families.update | App\Http\Controllers\FamiliesController#update | |
| | DELETE | employees/{employees}/families/{families} | employees.families.destroy | App\Http\Controllers\FamiliesController#destroy | |
| | GET|HEAD | employees/{employees}/families/{families} | employees.families.show | App\Http\Controllers\FamiliesController#show | |
| | PATCH | employees/{employees}/families/{families} | | App\Http\Controllers\FamiliesController#update | |
| | GET|HEAD | employees/{employees}/families/{families}/edit | employees.families.edit | App\Http\Controllers\FamiliesController#edit | |
| | GET|HEAD | employees/{id}/delete | | App\Http\Controllers\EmployeesController#delete | |
+--------+----------+------------------------------------------------+----------------------------+--------------------------------------------------+------------+
When i navigate to http://localhost/mysite/public/employees/1/families/create i can see the create form but it's not getting the employee data. i did a vardump of $employee on that page and i was expecting to see the data for EmployeeID = 1 (as you can see from the url), but it was blank. Funny thing is that it's not throwing an error, it receives the $employee data passed from the controller but it a blank data.
So what could be the problem?
The create method on the familiescontroller.php isn't getting which Employee we are using. The following is how the create method is supposed to be on
public function create($EmployeeID)
{
$employee = Employee::findOrFail($EmployeeID);
return view('families.create')->with('employee', $employee);
}
Question about Laravel's Eloquent ORM. I've had a look on SO already, apologies if I've missed a similar question.
I have a User model, and I'm trying to write an array of Permissions back to the UserPermissions model, via the relationship in the User model.
I've setup the hasMany link already, and can retrieve the correct data from the User object ($user->roles), but can't work out how to write back if it is at all possible.
This is my basic user model:
class User extends Eloquent {
protected $table = 'users';
public $timestamps = false;
protected function roles() {
return $this->hasMany('UserPermission');
}
}
and the UserPermission model:
class UserPermission extends Eloquent {
protected $table = 'users_permissions';
public $timestamps = false;
protected $fillable = ['role_id', 'user_id'];
}
At this stage, I've reverted to saving the User, and then running UserPermission::insert(), which allows an array to be passed, but I'd prefer to do it in one step if possible.
Anyone know if this is possible?
Thanks!
UPDATE:
Table structure is below for your perusal:
users table
+------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | 0 | auto_increment |
| username | varchar(255) | NO | | | |
+------------------+------------------+------+-----+---------+----------------+
users_roles table
+------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | 0 | auto_increment |
| name | varchar(255) | NO | | | |
| description | varchar(255) | YES | | NULL | |
| url_access | varchar(255) | NO | | | |
+------------------+------------------+------+-----+---------+----------------+
users_permissions table
+------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | 0 | auto_increment |
| role_id | int(10) unsigned | NO | | | |
| user_id | int(10) unsigned | NO | | | |
+------------------+------------------+------+-----+---------+----------------+
role_id relates to users_roles.id and user_id relates to users.id
As background logic, the users_roles table has a url_access column which contains a url. If the user is assigned to that role, they have access to the subpages from that url.
I do not really see why you are using hasMany relationship instead of belongsToMany. Actually it seems that your database structure is already such that is utilized by the belongsToMany relationship in Laravel.
My solution:
User.php
<?php
class User extends Eloquent {
public function roles() {
return $this->belongsToMany('Role');
}
protected $table = 'users';
protected $guarded = array('id', 'password');
}
Role.php
<?php
class Role extends Eloquent {
public function users()
{
return $this->belongsToMany('User');
}
protected $table = 'roles';
protected $guarded = array('id');
}
The corresponding database tables should be: users, roles and role_user. These are according to Laravel's naming conventions in order to keelp things simple.
Now you may call the sync method and pass an array to it:
$user->roles()->sync(array(1, 2, 3));
The sync method is briefly described in the Eloquent ORM documentation.
Okay here is what you could try.
Define a many to many relationship in both of the models.
class UserPermission extends Eloquent {
protected $table = 'users_permissions';
public $timestamps = false;
protected $fillable = ['role_id', 'user_id'];
protected function users() {
return $this->belongsToMany('User');
}
}
Then, if you create a user, use laravel attach method to connect a user to a users_permission like so:
$user = User::find(1);
$user->roles()->attach(1);
Attaching the role with an ID of 1 to the user with an ID of 1.
This is how you will be able to either attach a role to a user or attach a user to a role if you are creating a user or updating one.
I really hope that this is of help to you. If not, feel free to ask me further. I have defined many to many relations just a few days ago with photos and tags so I am quite into it I would say.
Also, the laravel docs even have an example with users and roles:
http://laravel.com/docs/eloquent#many-to-many
From reading your question it "sounds like" you are asking the same question I ran into the other day.
I hope this helps enable to you "bulk update" the relationships while maintaining timestamps and avoiding duplicate relationships.
Maybe there is a better way. I'm sure of it. But this worked perfectly for what I was trying to accomplish.
*Warning: this is not tested code. In fact the exact solution I used myself with some search/replace to help relate to your question
Class User extends BaseModel {
// [...]
public function roles() {
return $this->belongsToMany('Role');
}
public function addUserRoles(Array $add_user_role_ids) {
/**
* Prevent Duplicate Relationships
*/
$existing_user_role_ids = $this->roles()->lists('user_role_id');
$add_user_role_ids = array_diff($add_user_role_ids, $existing_user_role_ids);
if ($add_user_role_ids == null) return false;
$add_user_role_ids = UserRole::whereIn('id', $add_user_role_ids)->lists('id');
if ($add_user_role_ids == null) return false;
/**
* Attach (Insert into Pivot Table)
*/
if ( count($add_user_role_ids) > 0 ) {
$this->UserRoles()->attach($add_user_role_ids);
// Update timestamp
$this->touch();
}
// Return successfully added user role ids Array
return $add_user_role_ids;
}
public function removeUserRoles(Array $user_role_ids)
{
$this->touch();
$this->roles()->detach($user_role_ids);
}
// [...]
}
Eloquent Docs
Find me on Twitter: #ErikOnTheWeb