Laravel, pivot table conflicts with many-to-many relationship - laravel

Hey guys so I'm using spatie binary uuid package and I had few doubts
Things done so far:
User.php Migration:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->uuid('uuid');
$table->primary('uuid');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Role migration just have basic field called "name" with timestamps
Pivot table: role_user
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('role_id')->unsigned()->nullable()->index();
$table->uuid('user_uuid');
});
}
I know this is terribly wrong and I don't know what to do, I'm trying to save the Role model via this call
$uuid = '478d7068-ae64-11e8-a665-2c600cf6267b';
$model = User::withUuid($uuid)->first();
$model->roles()->save(new Role(['name' => 'Admin']));
it doesn't work, where am I going wrong? I think it has something to do with role_user migration
User.php
public function roles()
{
return $this->belongsToMany(Role::class);
}

try this, pivot migration:
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('role_id')->unsigned()->nullable()->index();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->uuid('user_uuid');
$table->foreign('user_uuid')->references('uuid')->on('users')->onDelete('cascade');
});
}
roles relation:
public function roles(){
return $this->belongsToMany(Role::class,'role_user','user_uuid','role_id');
}
please let me know if it didn't work

you should edit your relation to this
return $this->belongsToMany(Role::class,'role_user','user_uuid','role_id');
if you say about your error we better can help you

Related

Laravel 8 : SoftDeletes not updated when deleting a user linked to a form

I have a problem on Laravel 8 when I delete a user I have my 'deleted_at' which is updated in my 'user' table but not the 'deleted_at' of my 'forms' table because I want to delete the forms linked to this user otherwise I have an error because I display his info when he does not exist anymore.
How do I fix this problem please?
I have used the soft delete in the Models
and the 'deleted_at' is updated when I delete the form.
users migration :
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('firstname');
$table->string('lastname');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->foreignId('current_team_id')->nullable()->onDelete('cascade');
$table->string('profile_photo_path', 2048)->nullable();
$table->timestamps();
$table->foreignId('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->softDeletes();
});
}
public function down()
{
Schema::dropIfExists('users', function (Blueprint $table) {
$table->dropColumn('deleted_at');
});
}
forms migration :
public function up()
{
Schema::create('forms', function (Blueprint $table) {
$table->id();
$table->string('title', 100);
$table->text('message');
$table->datetime('date');
$table->string('color');
$table->softDeletes();
$table->timestamps();
});
}
public function down()
{
// Schema::dropIfExists('forms');
Schema::table('forms', function (Blueprint $table) {
$table->dropColumn('deleted_at');
});
}
add user to forms migration :
public function up()
{
Schema::table('forms', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
public function down()
{
Schema::table('forms', function (Blueprint $table) {
$table->dropForeign('user_id')->onDelete('cascade');
});
}
Soft delete won't work on cascading foreign keys. Cascading foreign keys is a feature of sql servers and soft delete is a feature of laravel and needs the laravel context to work.
When you delete it, for the soft deletes to work, you need to call delete on each model of the relation. This is quite easy with collections and higher order functions.
{
$user = User::firstOrFail($id);
$user->forms->each->delete();
$user->delete();
...
}
Thank you very much mrhn,
Thanks to you I have learned a lot!
For those which want the function in the controller which thus makes it possible to remove the user to which belongs thus the id and one thus removes also what is related to him in my case a forms (function in the Models for the cardinalities between entity) :
public function destroy($id)
{
// $users = User::findOrFail($id);
// $users->delete();
$user = User::findOrFail($id);
$user->forms->each->delete();
$user->delete();
return redirect()->route('admin');
}
findOrFail and not firstOrFail ^^'

Property [roles] does not exist on this collection instance. in a many-to-many relationship

Hello I am learning relationship many to many I read the official documentation and use the conventions,
but I can't make the relation many to many I get the error that the property does not exist.
how can I solve that?
Migrations
Schema::create('role_user', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
$table->foreignId('role_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
}
User
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();
});
}
Roles
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
Models:
User
public function roles(){
return $this->belongsToMany(role::class, 'role_user', 'user_id', 'role_id');
}
Role
public function users(){
return $this->belongsToMany(User::class, 'role_user','role_id','user_id');
}
query:
$v = User::get();
dd($v->roles);
$v = User::get(); returns a collection of users. If you get one user, for example, User::find(1) you will have access to the roles for this specific user.
Another option is
$users = User::with('roles')->get();
foreach ($users as $user) {
$userRoles = $user->roles;
}

Laravel get data from pivot table many to many relationship

Tables with relationship
I want to get the classes for specific notes. Here note id and class id are in a pivot table.
Note.php
public function classes()
{
return $this->belongsToMany(MyClass::class);
}
MyClass.php
public function notes()
{
return $this->belongsToMany(Note::class);
}
I am saving the data successfully by
$note->classes()->attach($request->class);
MyClass Migration
Schema::create('my_classes', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
$table->boolean('isDeleted')->default(false);
$table->dateTime('deletedAt')->nullable();
});
Notes Migration
Schema::create('notes', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('description')->nullable();
$table->string('image')->nullable();
$table->timestamps();
$table->boolean('isDeleted')->default(false);
$table->dateTime('deletedAt')->nullable();
});
my_class_note migration
Schema::create('my_class_note', function (Blueprint $table) {
$table->bigIncrements('id');
$table->foreignId('my_class_id')->constrained();
$table->foreignId('note_id')->constrained();
$table->timestamps();
});
Needed help on getting classes for a specific note. One note can have many classes.
You can simply access it by using the relationship property, there always will be if you have defined a relationship.
// returns a collection of classes
$classes = Note::find(1)->classes;
In your controller.
return view('yourview', ['classes' => $classes]);
In your view.
#foreach($classes as $class)
<p>{{$class->name}}</p>
#endforeach

BadMethodCallException: Trying to list all partners with the categories laravel

I'm experiencing the following:
Goal: I would like to list all partners and the categories they belong to. Basically, it's a many to many relationship.
Below is the code:
Partner Categories Table Migration
public function up()
{
Schema::create('partcats', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('partcatnameP')->unique();
$table->unsignedBigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
Partners Table Migration
public function up()
{
Schema::create('partners', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('partnername');
$table->string('regnumber')->unique();
$table->unsignedBigInteger('activestatus_id')->unsigned();
$table->foreign('activestatus_id')->references('id')->on('activestatuses');
$table->unsignedBigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
Partner_Category Migration
public function up()
{
Schema::create('partner_partcat', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('partner_id')->unsigned();
$table->foreign('partner_id')->references('id')->on('partners')->onDelete('cascade');
$table->unsignedBigInteger('partcat_id')->unsigned();
$table->foreign('partcat_id')->references('id')->on('partcats')->onDelete('cascade');
$table->timestamps();
});
}
Models are as shown below:
Partcat Model
public function partners()
{
return $this->belongsToMany('App\Partcat','partner_partcat');
}
Partner Model
public function partcats()
{
return $this->belongsToMany('App\Partcat','partner_partcat');
}
and the Partners Controller is as shown below:
public function index()
{
//
$partners = Partner::all()->partcats();
// dd(Partner::all()->partcats());
return view('partners.index',['partners'=>$partners]);
}
This is where I'm trying to retrieve the list of partners and its related categories. However, I get a BadMethod call error.
You can use the following method
$partners = Partner::with('partcats')->get();
https://laravel.com/docs/5.6/eloquent-relationships#eager-loading
A many to many pivot table typically has the id for both tables it is relating.
The Partner_Category migration you have posted only seems to contain a partner_id. You may need to add in the category_id.
public function up()
{
Schema::create('partner_partcat', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('partner_id')->unsigned();
$table->unsignedBigInteger('partcat_id')->unsigned();
$table->timestamps();
$table->foreign('partner_id')->references('id')->on('partners')->onDelete('cascade');
$table->foreign('partcat_id')->references('id')->on('partcats')->onDelete('cascade');
});
}

Eloquent relationship property access

Cant seem to figure out the probleme here, getting error - Trying to get property 'name' of non-object
User DB
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('lastname');
$table->string('email')->unique();
$table->string('password');
$table->integer('phone');
$table->boolean('isAdmin')->default(0);
$table->rememberToken();
$table->timestamps();
});
Sludinajums DB
Schema::create('sludinajums', function (Blueprint $table) {
$table->increments('id');
$table->string('logo');
$table->string('nosaukums');
$table->string('regnr');
$table->string('text');
$table->string('atrasanasVieta');
$table->string('adrese');
$table->integer('telefons');
$table->string('epasts');
$table->integer('profesija_id')->unsigned();
$table->foreign('profesija_id')->references('id')->on('profesijas')->onDelete('cascade');
$table->integer('lietotajs_id')->unsigned();
$table->foreign('lietotajs_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
User model function
public function sludinajums()
{
return $this->hasOne(sludinajums::class,'lietotajs_id');
}
Sludinajums model function
public function user()
{
return $this->belongsTo('App\User');
}
Here is my controller function
public function sludinajuma_skats($id){
$slud = sludinajums::where('id',$id)->with('user')->get();
return view('views.sludinajums', compact('slud'));
}
And in my view im trying to access name attribute from User table.
{{dd($sl->user->name)}}
try this for Sludinajums model function
public function user()
{
return $this->hasMany('App\User','lietotajs_id');
}

Resources