Laravel - get data out from many to many relations - php

I have a many to many relation
public function products()
{
return $this->belongsToMany(Product::class); // relation between books and categories
}
public function parts()
{
return $this->belongsToMany(Part::class); // relation between books and categories
}
my migrations :
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->string('link')->default('anohe.com');
$table->string('pname')->default('product');
$table->timestamps();
$table->string('description',3000)->nullable();
$table->string('smalldescription',500)->nullable();
});
}
public function up()
{
Schema::create('parts', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
public function up()
{
Schema::create('part_product', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('product_id');
$table->unsignedInteger('part_id');
$table->timestamps();
$table
->foreign('product_id')
->references('id')
->on('products')
->onDelete('cascade');
$table
->foreign('part_id')
->references('id')
->on('parts')
->onDelete('cascade');
});
}
How can I get products that have a special part_id?

If your relations are correct, that should work:
$specialPartIds = [1];
$products = Product::whereHas('parts', function ($query) use ($specialPartIds) {
$query->whereIn('id', $specialPartIds);
})->get();
dd($products->toArray());

Related

Laravel authentication with multiple roles

Hi I'm a beginner at laravel, I have to develop a project for human resources management and I have two roles admin and employee. I followed a tutorial at laracast to build roles and abilities table and everything seems to be working. Now I just installed laravel/ui package and I can see login and register which are working fine with the users I registered in the database. My problem now is that I don't know how to connect things together. How can I check if the logged in user is admin so the admin panel opens. Waiting for your replies. Here is the code;
Error I'm receiving: 419 page expired
This is what I tried but doesn't work
protected function authenticated(Request $request, $user)
{
// to admin dashboard
if(auth()->user()->roles()->name === 'admin') {
return redirect(route('admin'));
}
// to user dashboard
else if(auth()->user()-roles()->name === 'user') {
return redirect(route('home'));
}
abort(404);
}
Routes
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/admin', 'LoginController#authenticated')->name('admin');
users table
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
create roles table
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('label')->nullable();
$table->timestamps();
});
Schema::create('abilities', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('label')->nullable();
$table->timestamps();
});
Schema::create('ability_role', function (Blueprint $table) {
$table->primary(['role_id','ability_id']);
$table->unsignedBigInteger('role_id');
$table->unsignedBigInteger('ability_id');
$table->timestamps();
$table->foreign('role_id')
->references('id')
->on('roles')
->onDelete('cascade');
$table->foreign('ability_id')
->references('id')
->on('roles')
->onDelete('cascade');
});
Schema::create('role_user', function (Blueprint $table) {
$table->primary(['user_id','role_id']);
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('role_id');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('role_id')
->references('id')
->on('roles')
->onDelete('cascade');
});
}
User.php
public function roles()
{
if(is_string($role))
{
$role = Role::whereName($role)->firstOrFail();
}
return $this->belongsToMany(Role::class)->withTimestamps();
}
public function assignRole($role)
{
$this->roles()->sync($role, false);
}
public function abilities($role)
{
return $this->roles->map->abilities->flatten()->pluck('name')->unique();
}
Role.php
class Role extends Model
{
protected $guarded = [];
public function abilities()
{
return $this->belongsToMany(Ability::class)->withTimestamps();
}
public function allowTo($ability)
{
$this->abilities()->sync($ability,false);
}
}
Ability.php
{
protected $guarded = [];
public function roles()
{
if(is_string($ability))
{
$ability = Ability::whereName($ability)->firstOrFail();
}
return $this->belongsToMany(Role::class)->withTimestamps();
}
}
To management roles and permissions I'm using:
"santigarcor/laratrust"
You can learn more here: https://github.com/santigarcor/laratrust
You can use it like this:
use Illuminate\Support\Facades\Auth;
if (Auth::user()->isAbleTo('edit-user')) {}
if (Auth::user()->hasRole('admin')) {}
if (Auth::user()->isA('guide')) {}
if (Auth::user()->isAn('admin')) {}
This package provides a user interface for the santigarcor/laratrust package
"icweb/trusty"
You can learn more here: https://github.com/icweb/laratrust-ui
All tables and data will be auto created.

How to just update a table and add new line with Laravel?

in the database table as below;
public function up()
{
Schema::create('current_adresses', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('current_name',50)->nullable();
$table->string('current_surname',50)->nullable();
$table->string('telephone',25)->nullable();
$table->timestamps();
});
}
I want to do as below;
public function up()
{
Schema::create('current_adresses', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('current_name',50)->nullable();
$table->string('current_surname',50)->nullable();
$table->string('gsm',25)->nullable();
$table->string('telephone',25)->nullable();
$table->timestamps();
});
}
how can I update the new column(gsm column) without refreshing(php artisan migrate:refresh)
Add new migration-
public function up()
{
Schema::table('current_adresses', function($table) {
$table->string('gsm',25)->nullable();
});
}
public function down()
{
Schema::table('current_adresses', function($table) {
$table->dropColumn('gsm');
});
}
See this link for better understanding.

one to many And one to many relationship laravel

This is projects migrate
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('start_date');
$table->string('end_date');
$table->string('con');
$table->timestamps();
});
and this is timesheets migrate
Schema::create('timesheets', function (Blueprint $table) {
$table->increments('id');
$table->string('user_id');
$table->string('project_id');
$table->string('day');
$table->string('month');
$table->string('year');
$table->string('jalali');
$table->string('timesheet_h');
$table->string('timesheet_m');
$table->timestamps();
});
and this users migrate
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('mobile');
$table->string('salary_base');
$table->string('salary_base_h');
$table->string('start_contract');
$table->string('end_contract');
$table->string('start_insurance');
$table->string('end_insurance')->nullable();
$table->string('first_salary');
$table->string('date_birth');
$table->string('melli_code');
$table->string('s_number');
$table->string('nda');
$table->string('work_rules');
$table->string('end_work')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
This my project model
public function timesheets()
{
return $this->hasMany(timesheet::class,'project_id');
}
This my timesheet model :
public function projects()
{
return $this->belongsTo(project::class,'project_id');
}
public function users()
{
return $this->belongsTo(User::class,'user_id','id');
}
and This my User model
public function project_peoples()
{
return $this->hasMany('App\project_people');
}
public function timesheets()
{
return $this->belongsTo(timesheet::class);
}
public function projects()
{
return $this->belongsTo(project::class);
}
Now I return my query from projects
public function allProject()
{
$projects=project::with(['timesheets','users'])->get();
return $projects;
}
This is ok but user_id Users in timesheets.user_id And I can not get it out timesheets and get it
This controller return project and timesheet by project_id in timesheet but user_id in timesheet I do not know how to get this into the system
Use dot syntax to load nested relationships:
project::with('timesheets.users')->get();
[{"id":1,"name":"\u067e\u0631\u0648\u0698\u0647 \u062a\u0627\u06cc\u0645 \u0634\u06cc\u062a","start_date":"1111\/11\/11","end_date":"1111\/11\/11","con":"\u062f\u0631\u062d\u0627\u0644 \u0627\u062c\u0631\u0627","created_at":"2018-01-02 10:54:11","updated_at":"2018-01-02 10:54:11","timesheets":[{"id":7,"user_id":"2","project_id":"1","day":"12","month":"10","year":"1396","jalali":"1396\/10\/12","timesheet_h":"5","timesheet_m":"24","created_at":"2018-01-02 12:40:12","updated_at":"2018-01-02 13:47:09","users":{"id":2,"name":"\u0645\u0633\u0639\u0648\u062f \u0633\u0644\u06cc\u0645\u0627\u0646\u06cc","mobile":"0000","salary_base":"1000000","salary_base_h":"20000","start_contract":"1111\/11\/11","end_contract":"1000\/00\/00","start_insurance":"1111\/11\/11","end_insurance":null,"first_salary":"100000","date_birth":"1111\/11\/11","melli_code":"1212","s_number":"1212","nda":"\u062f\u0627\u0631\u062f","work_rules":"\u062f\u0627\u0631\u062f","end_work":null,"created_at":"2018-01-02 12:36:07","updated_at":"2018-01-02 12:36:07"}},{"id":8,"user_id":"1","project_id":"1","day":"13","month":"10","year":"1396","jalali":"1396\/10\/13","timesheet_h":"10","timesheet_m":"10","created_at":"2018-01-03 05:59:13","updated_at":"2018-01-03 05:59:13","users":{"id":1,"name":"\u0645\u062c\u06cc\u062f \u0641\u06cc\u0636\u06cc","mobile":"00","salary_base":"3000000","salary_base_h":"10000","start_contract":"1111\/11\/11","end_contract":"1111\/11\/11","start_insurance":"1111\/11\/11","end_insurance":null,"first_salary":"100000","date_birth":"1111\/11\/11","melli_code":"00","s_number":"00","nda":"\u062f\u0627\u0631\u062f","work_rules":"\u062f\u0627\u0631\u062f","end_work":null,"created_at":"2018-01-02 10:53:48","updated_at":"2018-01-02 10:53:48"}},{"id":9,"user_id":"2","project_id":"1","day":"14","month":"10","year":"1396","jalali":"1396\/10\/14","timesheet_h":"10","timesheet_m":"15","created_at":"2018-01-04 07:17:44","updated_at":"2018-01-04 07:17:44","users":{"id":2,"name":"\u0645\u0633\u0639\u0648\u062f \u0633\u0644\u06cc\u0645\u0627\u0646\u06cc","mobile":"0000","salary_base":"1000000","salary_base_h":"20000","start_contract":"1111\/11\/11","end_contract":"1000\/00\/00","start_insurance":"1111\/11\/11","end_insurance":null,"first_salary":"100000","date_birth":"1111\/11\/11","melli_code":"1212","s_number":"1212","nda":"\u062f\u0627\u0631\u062f","work_rules":"\u062f\u0627\u0631\u062f","end_work":null,"created_at":"2018-01-02 12:36:07","updated_at":"2018-01-02 12:36:07"}},{"id":10,"user_id":"2","project_id":"1","day":"16","month":"10","year":"1396","jalali":"1396\/10\/16","timesheet_h":"10","timesheet_m":"60","created_at":"2018-01-06 07:17:21","updated_at":"2018-01-06 07:17:21","users":{"id":2,"name":"\u0645\u0633\u0639\u0648\u062f \u0633\u0644\u06cc\u0645\u0627\u0646\u06cc","mobile":"0000","salary_base":"1000000","salary_base_h":"20000","start_contract":"1111\/11\/11","end_contract":"1000\/00\/00","start_insurance":"1111\/11\/11","end_insurance":null,"first_salary":"100000","date_birth":"1111\/11\/11","melli_code":"1212","s_number":"1212","nda":"\u062f\u0627\u0631\u062f","work_rules":"\u062f\u0627\u0631\u062f","end_work":null,"created_at":"2018-01-02 12:36:07","updated_at":"2018-01-02 12:36:07"}}]},{"id":2,"name":"\u067e\u0631\u0648\u0698\u0647 \u062a\u0633\u062a\u06cc","start_date":"1111\/11\/11","end_date":"1111\/11\/11","con":"\u062f\u0631\u062d\u0627\u0644 \u0627\u062c\u0631\u0627","created_at":"2018-01-02 11:28:03","updated_at":"2018-01-02 11:28:03","timesheets":[{"id":3,"user_id":"1","project_id":"2","day":"12","month":"10","year":"1396","jalali":"1396\/10\/11","timesheet_h":"8","timesheet_m":"12","created_at":"2018-01-02 11:39:46","updated_at":"2018-01-02 11:39:46","users":{"id":1,"name":"\u0645\u062c\u06cc\u062f \u0641\u06cc\u0636\u06cc","mobile":"00","salary_base":"3000000","salary_base_h":"10000","start_contract":"1111\/11\/11","end_contract":"1111\/11\/11","start_insurance":"1111\/11\/11","end_insurance":null,"first_salary":"100000","date_birth":"1111\/11\/11","melli_code":"00","s_number":"00","nda":"\u062f\u0627\u0631\u062f","work_rules":"\u062f\u0627\u0631\u062f","end_work":null,"created_at":"2018-01-02 10:53:48","updated_at":"2018-01-02 10:53:48"}},{"id":4,"user_id":"1","project_id":"2","day":"12","month":"10","year":"1396","jalali":"1396\/10\/10","timesheet_h":"4","timesheet_m":"11","created_at":"2018-01-02 11:40:41","updated_at":"2018-01-02 13:49:45","users":{"id":1,"name":"\u0645\u062c\u06cc\u062f \u0641\u06cc\u0636\u06cc","mobile":"00","salary_base":"3000000","salary_base_h":"10000","start_contract":"1111\/11\/11","end_contract":"1111\/11\/11","start_insurance":"1111\/11\/11","end_insurance":null,"first_salary":"100000","date_birth":"1111\/11\/11","melli_code":"00","s_number":"00","nda":"\u062f\u0627\u0631\u062f","work_rules":"\u062f\u0627\u0631\u062f","end_work":null,"created_at":"2018-01-02 10:53:48","updated_at":"2018-01-02 10:53:48"}},{"id":6,"user_id":"1","project_id":"2","day":"12","month":"10","year":"1396","jalali":"1396\/10\/12","timesheet_h":"1","timesheet_m":"12","created_at":"2018-01-02 12:06:31","updated_at":"2018-01-02 13:49:37","users":{"id":1,"name":"\u0645\u062c\u06cc\u062f \u0641\u06cc\u0636\u06cc","mobile":"00","salary_base":"3000000","salary_base_h":"10000","start_contract":"1111\/11\/11","end_contract":"1111\/11\/11","start_insurance":"1111\/11\/11","end_insurance":null,"first_salary":"100000","date_birth":"1111\/11\/11","melli_code":"00","s_number":"00","nda":"\u062f\u0627\u0631\u062f","work_rules":"\u062f\u0627\u0631\u062f","end_work":null,"created_at":"2018-01-02 10:53:48","updated_at":"2018-01-02 10:53:48"}}]}]
This is my return i have 2 users but repeat my 2 users :(

Laravel relationship belongsToMany with composite primary keys

I have 3 tables and I'm trying to make relations between order_products and order_products_status_names. I have transition/pivot table named order_product_statuses. The problem are my PK, becuase I have in table orders 3 Pk, and I don't know how to connect this 3 tables throught relationships.
My migrations are:
Table Order Products:
public function up()
{
Schema::create('order_products', function (Blueprint $table) {
$table->integer('order_id')->unsigned();
$table->integer('product_id')->unsigned();
$table->integer('ordinal')->unsigned();
$table->integer('size');
$table->primary(['order_id', 'product_id', 'ordinal']);
$table->foreign('order_id')->references('id')->on('orders');
$table->foreign('product_id')->references('id')->on('products');
});
}
Table Order Product Statuses - this is my transition/pivot table between order_products and order_product_status_names
public function up()
{
Schema::create('order_product_statuses', function (Blueprint $table) {
$table->integer('order_id')->unsigned();
$table->integer('product_id')->unsigned();
$table->integer('status_id')->unsigned();
$table->integer('ordinal')->unsigned();
$table->dateTime('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->foreign('order_id')->references('id')->on('orders');
$table->foreign('status_id')->references('id')->on('order_product_status_names');
$table->primary(['order_id', 'product_id', 'ordinal']);
});
}
And the last one is Order Product Status Names
public function up()
{
Schema::create('order_product_status_names', function (Blueprint $table) {
$table->integer('id')->unsigned();
$table->string('name');
$table->string('code');
$table->dateTime('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->primary('id');
});
}
I know that here is relationship blengsToMany in two ways, but I don't know or can I declarate this relation ( from order_products to order_product_status_names and inverse )?
Ok haven't spent a great amount of time on this, but this is kind of what I would do. Also as #Devon mentioned I would probably add ids to each table seeing as Eloquent isn't really designed for composite keys. As mentioned in one of my comments I usually create startup and update scripts, so the syntax might not be exactly right:
public function up() {
Schema::create('order_products', function (Blueprint $table) {
$table->bigIncrements('id')->unsigned();
$table->integer('order_id')->unsigned();
$table->integer('product_id')->unsigned();
$table->integer('order_product_statuses_id')->unsigned();
$table->integer('ordinal')->unsigned();
$table->integer('size');
$table->primary('id');
$table->foreign('order_id')->references('id')->on('orders');
$table->foreign('product_id')->references('id')->on('products');
$table->foreign('order_product_statuses_id')->references('id')->on('order_product_statuses');
});
}
public function up() {
Schema::create('order_product_statuses', function (Blueprint $table) {
$table->bigIncrements('id')->unsigned();
$table->integer('product_id')->unsigned();
$table->integer('status_id')->unsigned();
$table->integer('ordinal')->unsigned();
$table->dateTime('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->primary('id');
$table->foreign('status_id')->references('id')->on('order_product_status_names');
});
}
public function up() {
Schema::create('order_product_status_names', function (Blueprint $table) {
$table->bigIncrements('id')->unsigned();
$table->string('name');
$table->string('code');
$table->dateTime('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->primary('id');
});
}
I hope that helps you out a bit.

Laravel Many to Many Relationship Users on Shift

I'm trying to get the users that are on today's shift. I have a many to many relationship between the User and Shift model with a pivot table called user_shifts.
My User model:
/**
* Get the users shifts
*/
public function shift()
{
return $this->belongsToMany('App\Shift', 'user_shifts', 'user_id', 'shift_id');
}
My Shift model
/**
* The shift can have many users
*/
public function users()
{
return $this->belongsToMany('App\User', 'user_shifts', 'shift_id', 'user_id')->withPivot('start_time', 'end_time');;
}
In my controller I thought I could do something like:
$shift = Shift::all()->where('date', date('Y-m-d'));
$users = User::all()->where('shift_id', $shift);
return $users;
But that is returning null. Any help would be appreciated!
If it matters my db schema is:
Schema::create('shifts', function (Blueprint $table) {
$table->increments('id');
$table->date('date');
$table->boolean('weekend');
});
Schema::create('user_shifts', function (Blueprint $table) {
$table->increments('id');
$table->integer('shift_id');
$table->integer('user_id');
$table->time('start_time');
$table->time('end_time');
});
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('fname');
$table->string('lname');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});

Categories