¿Como puedo actualizar campos de tabla pivot con SYNC laravel?
Hola,
No estoy seguro si estoy planteando bien mi pregunta, pero anexo lo que tengo
Quiero registrar un nuevo pago y a la ves actualizar el ROL de el usuario que lo registro.
Intento registrar el pago asi:
$payment = payment::create($request->all());
Un dd de ese codigo me regresa lo siguiente:
App\Payment {#1410 ▼
#fillable: array:5 [▶]
#connection: "mysql"
#table: "payments"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: true
#attributes: array:8 [▶]
#original: array:8 [▼
"user_id" => "14"
"tpaid_id" => "2"
"vouche" => "5345435"
"description" => "543535"
"status" => "pass"
"updated_at" => "2020-10-22 23:00:34"
"created_at" => "2020-10-22 23:00:34"
"id" => 108
]
Hasta ahi todo bien, porque si lo agrega en la base de datos.
Mi necesidad es actualizar el tipo de rol de un usuario en específico.
$role = Role::find($roles); //puedo buscar el tipo de rol
Ahora, tengo que buscar el $user_id en la tabla role_user, que es donde estan la tabla pivot
modelo payment
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Caffeinated\Shinobi\Concerns\HasRolesAndPermissions;
class Payment extends Model
{
use Notifiable, HasRolesAndPermissions;
protected $fillable=['tpaid_id','user_id','vouche','description','status'];
public function tipopago(){
return $this->hasOne(Tpaid::class, 'id','tpaid_id');
}
public function usuario(){
return $this->hasOne(User::class, 'id','user_id');
}
}
modelo USER
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Notifications\UserResetPassword;
use App\Notifications\VerifyEmails;
use Caffeinated\Shinobi\Concerns\HasRolesAndPermissions;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable, HasRolesAndPermissions;
public function sendEmailVerificationNotification()
{
$this->notify(new VerifyEmails);
}
public function sendPasswordResetNotification($token)
{
$this->notify(new UserResetPassword($token));
}
public function payments(){
return $this->belongsTo(Payment::class, 'id','user_id');
}
/**
* The attributes that are mass assignable.
*
* @var array
*/
//Aqui son los datos que se dan de alta para interactuar con el formulario y Contorlador
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Anexo el modelo ROLES del paquete shinobi/caffeinate
<?php
namespace Caffeinated\Shinobi\Models;
use Illuminate\Database\Eloquent\Model;
use Caffeinated\Shinobi\Concerns\HasPermissions;
use Caffeinated\Shinobi\Contracts\Role as RoleContract;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Role extends Model implements RoleContract
{
use HasPermissions;
/**
* The attributes that are fillable via mass assignment.
*
* @var array
*/
protected $fillable = ['name', 'slug', 'description', 'special'];
/**
* Create a new Role instance.
*
* @param array $attributes
* @return void
*/
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->setTable(config('shinobi.tables.roles'));
}
/**
* Roles can belong to many users.
*
* @return Model
*/
public function users(): BelongsToMany
{
return $this->belongsToMany(config('auth.model') ?: config('auth.providers.users.model'))->withTimestamps();
}
/**
* Determine if role has permission flags.
*
* @return bool
*/
public function hasPermissionFlags(): bool
{
return ! is_null($this->special);
}
/**
* Determine if the requested permission is permitted or denied
* through a special role flag.
*
* @return bool
*/
public function hasPermissionThroughFlag(): bool
{
if ($this->hasPermissionFlags()) {
return ! ($this->special === 'no-access');
}
return true;
}
}
¿Es posible hacerlo de otra forma y utilizando transacciones?
Saludos
$roles = array($request->role_id); $users = array($payment->user_id);
,$user->roles()->attach($users, $roles);
y me da el siguiente error,SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: insert into
role_user` (role_id
,user_id
,0
) values (19, ?, 12))` . Realice cambios y lo ejecuto asi. Creo que no estoy entendiendo el metodo.