0
votes

I am working with Laravel 5.6 and MySQL. in My app I have some data edit form and its updated values saving with 3 different tables. called vehicles, cars and upload My edit form url as following,

http://localhost:8000/myads/1/edit

number (1) is vehicle table id number, like this,

id    name         owner  
1     toyota        dane
2     BMW           peter
3     Benz          samantha
4     volvo         Alex

and car table is like this,

id     fuel    vehicle_id
1       P              1
2       D              3
3       E              2

I need update cars table data with regarding to vehicle_id , My VehicleController vehicle table data update function is like this

public function update(Request $request, $id)
    {
        $vehicle = Vehicle::find($id);

        $vehicle->name = $request->input('name');
        $vehicle->owner = $request->input('owner');

        $vehicle->save();
}

now I need update cars table fuel values with same form optional values input. how can I do this in the Controller?

My fuel selection input is like this,

<div class="form-group">
        <label for="exampleFormControlSelect1">Fuel</label>
        <select class="form-control" id="fuel" name="fuel">
            @foreach($vehicles->cars as $car)
            <option value="{!! $car->fuel  !!}">{!! $car->fuel  !!}</option>
            @endforeach 
        <option value="P">Petrol</option>
        <option value="D">Diesel</option>
        <option value="H">Hybrid</option>
        <option value="E">Electric</option>

        </select>
        </div> 

relationship among Vehicle and Car Models are

Vehicle Model

public function cars()
    {
        return $this->hasMany(Car::class);
    }

Car Model

public function vehicle()
    {
        return $this->belongsTo(Vehicle::class);
    }

How can do it?

2

2 Answers

0
votes

Use a hidden Input field (load car id to the input using $car->id ) in form and name it as 'car_id'. In the same update function,

 $carId = $request->input('car_id');
 $car= Car::find($carId);
 //Update details here
 $car->save();

Note : when you are working with multiple table, do not forget to use DB Transaction.

0
votes

got success with following codes,

$vehicle->cars()->where('vehicle_id', $id)->update(['fuel' => $request->input('fuel')]);