简体   繁体   中英

Laravel insert record with one to many relationship

I have two tables car_category and vehicles and set the car Id as foreign key constraint of vehicles table's c_id.Now I want to add vehicles to vehicles table with the relationship.So I want to store the vehicle details,How 'ld I add the fk constraint to my controller? I've set the relationship between tables like, In Car model,

class car extends Model
{
    protected $guarded = [];
    protected $table = 'car_category';

    public function vehicles()
    {
        return $this->hasMany('Vehicle');
    }
}

Vehicle Model,

class Vehicle extends Model
{
    protected $guarded = [];
    protected $table = 'vehicles';

    public function cars()
    {
        return $this->belongsTo('Car');
    }
}

And store vehicle details like,

public function store(Request $request)
{
    $this->validate($request, [
        'vehicle_no' => 'required',
        'vehicle_company' => 'required',
        'vehicle_category' => 'required',
        'vehicle_type' => 'required',
        'vehicle_model' => 'required',
        'vehicle_capacity' => 'required',
        'vehicle_color' => 'required',
        'c_cid' => '',
    ]);

    Vehicle::create($request->all());
            return redirect()->route('vehicles.index')
                 ->with('success','Vehicle details stored successfully');
}

How to pass the fk constraint value?Can anybody help me?

Try adding the car field in you form, you can get the ID while saving the vehicle

    <div class="col-md-6"> 
        <select name="c_id" class="form-control"> 
        @foreach($car as $cars) 
            <option value="{{ $cars->id }}">{{ $cars->Name }}</option> 
        @endforeach </select> 
    </div>

here you can get the value in

public function store(Request $request) {
    // here you can get the value
    $request->c_id;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM