Laravel 5.4 - 雄辩的关系更新
我有一个关于在Laravel中更新表格的问题。我有一个和模型。示例如下,User
Car
用户.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $guarded = [];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function cars()
{
return $this->hasMany(Car::class);
}
}
汽车.php
<?php
namespace App;
class Car extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
对于更新,我在控制器上使用以下代码,
public function update(Request $request, $id)
{
// validations here
$car = Car::find($id);
$carDetail = Car::where('id', $id)
->update([
'vehicle_no'=> $request->vehicle_no,
'location_id' => $request->location_id,
'created_at' => $request->created_at,
]);
$user = $car->user()
->update([
'name'=> $request->name,
'ic_number'=> $request->ic_number,
]);
return back();
}
我可以更新表格,但想知道我是否做对了。
有没有准确或更好的方法来做到这一点。