vendredi 24 novembre 2017

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?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire