jeudi 2 août 2018

Correct way of updating, storing and deleting in many-to-many relationship in Laravel 5.6

I have this code and it's kinda working for storing and update but I don't know how to delete user's role by detach method. How can I delete a single role from multiple user's role? I am not sure about the codes along the roles()->attach() line which and I think you guys have a better solution to this.

UsersController:

public function store(Request $request)
{

    if($request->isMethod('put'))
    {
        $user = User::findOrFail($request->id);
        $user->name = $request->input('name');
        $user->email = $request->input('email');
        $role = Role::where('name',$request->input('role_id'))->first();
        $user->roles()->attach($role->id);
    }
    else
    {
        $user = new User;
        $user->name = $request->input('name');
        $user->email = $request->input('email');
        $user->password = Hash::make($request->input('password'));
        $user->remember_token = str_random(40);
        $user->id = User::count() + 1; //get the last user id? for pivot table
        $user->roles()->attach(2); //default role (2) : admin is (1)
    }

    if($user->save()){
        return response()->json($user);
    }
}

User.php

  public function roles(){
      return $this->belongsToMany('App\Role');
  }

Role.php

  public function users(){
      return $this->belongsToMany('App\User');
  }

Pivot table

   Schema::create('role_user', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->integer('role_id')->unsigned();
   });



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2KlhKks
via IFTTT

Aucun commentaire:

Enregistrer un commentaire