I have a question on updating a table in Laravel. I have a User and Car Model. Example as below,
User.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);
}
}
Car.php
<?php
namespace App;
class Car extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
For the update, I am using below codes on my controller,
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();
}
I am able to update the table but want to know if I am doing it right.
Is there an accurate or a better way of doing it.