2017-11-20 1 views
0

Laravel의 테이블을 업데이트하는 데 질문이 있습니다. 나는 UserCar 모델을 가지고있다. 예Laravel 5.4 - Eloquent Relationship Update

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); 
    } 
} 

업데이트에 대한

<?php 

namespace App; 

class Car extends Model 
{ 
    public function user() 
    { 
     return $this->belongsTo(User::class); 
    }  
} 

Car.php, 나는 내 컨트롤러에 코드 아래 사용하고

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(); 
} 

나는 할 수있다. 테이블을 pdate해라. 그러나 내가 그것을 올바르게하고 있는지에 관해 알고 싶다.

정확하고 나은 방법이 있습니까?

답변

4

두 모델 사이의 관계를 사용하는 경우 릴레이션에 포함 된 관계를 업데이트 할 때 더 좋습니다. 네, 거의 맞습니다. 컨트롤러에서와 다른 별도의 REQUEST 파일을 사용하면 더 많은 정보를 얻을 수 있습니다. 경험을 바탕으로 한 가지 더 중요한 것은 관계를 먼저 업데이트 할 때 더 좋습니다. 답에 대한

public function update(SomeRequestFile $request, $id) 

{

$car = Car::find($id); 

$user = $car->user() 
    ->update([ 
     'name'=> $request->name, 
     'ic_number'=> $request->ic_number, 
    ]); 
    $carDetail = Car::where('id', $id) 
    ->update([ 
     'vehicle_no'=> $request->vehicle_no, 
     'location_id' => $request->location_id, 
     'created_at' => $request->created_at, 
    ]); 



    return back(); 

}

+0

감사 : 전반적는 다음과 같이 될 것입니다. 별도의 요청 파일과 관련하여 다른 방법으로 파일을 분리해야합니까? – Khairul

+0

@Khairul 아니, 내 말은 이런 뜻이야. php artisan make : SomethingRequest를 요청하면 더 많은 정보를 얻기 위해 거기에서 유효성 검사를 수정할 수 있습니다. https : //laravel.com/docs/5.5/validation#creating-form-requests ..이 도움을 바란다. –