1
What’s the best way to make one update in two tables at the same time? I thought it was just to call the related table, but when I do it only makes the update on the table service and not in the client.
I managed to pass the customer id to view and then taking it and inserting it into Where to make the update(as shown by the other example), but I would like to know if it is possible to do the update in both tables without informing the foreign key code.
CLIENT CONTROLLER (Running)
public function update(Request $request, $id)
{
$dataForm = $request->all();
$cliente_id = $request->input('cliente_id');
Servico::find($id)->update($dataForm);
Cliente::find($cliente_id)->update($dataForm);
return redirect()->route('index');
}
CLIENT CONTROLLER (Not working)
public function update(Request $request, $id)
{
$dataForm = $request->all();
Servico::with('cliente')->find($id)->update($dataForm);
return redirect()->route('index');
}
CUSTOMER MODEL
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Cliente extends Model
{
protected $primaryKey = 'id';
protected $table = 'clientes';
protected $fillable = ['nome', 'fone'];
protected $dates = ['created_at', 'updated_at'];
public $timestamps = true;
public function servicos()
{
return $this->hasMany('App\Models\Servico');
}
}
MODEL SERVICE
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Servico extends Model
{
protected $primaryKey = 'id';
protected $table = 'servicos';
protected $fillable = ['valor', 'descricao', 'cliente_id', 'data_fechamento'];
protected $dates = ['created_at', 'updated_at', 'data_fechamento'];
public $timestamps = true;
public function cliente()
{
return $this->belongsTo('App\Models\Cliente');
}
}
Do you want Customer Service where 1 service is 1 customer?
– novic
That, a service belongs to 1 customer, but a customer can have several services.
– Diego Vieira
When I edit a service, I can change the service information (value, description) and customer data(name, phone).
– Diego Vieira
You can, Diego. Normally, just don’t forget to set up
fillable
!– novic
It worked @Diego?
– novic