0
votes

Create hasmany relatioship in vehicle model and insert data in vehicle and vehicle_staff table. data successfully insert in vehicle table but when store in vehicle_staff following error appear.

Error Comes:

Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, array given, called in E:\xampp\htdocs\laravel-projects\collegeaccounting\app\Http\Controllers\Transport\VehicleController.php on line 53

Vehicle Staff Table Schema:

Schema::create('vehicle_staffs', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();

            $table->unsignedInteger('vehicles_id');
            $table->unsignedInteger('staffs_id');

            $table->boolean('status')->default(1);
        });

Has Many Relationship on Vehicle Model:

 class Vehicle extends BaseModel
{
    protected $fillable = ['created_by', 'last_updated_by', 'number', 'type', 'model', 'description', 'status'];

    public function staff(){
        return $this->hasMany(Staff::class);
    }
}

Store Function:

public function store(AddValidation $request)
    {
        $request->request->add(['created_by' => auth()->user()->id]);

        $vehicle =  Vehicle::create($request->all());

        if ($request->has('staffs_id')) {
            $staffs = [];
            foreach ($request->get('staffs_id') as $staff) {
                $staffs[$staff] = ([
                    'vehicles_id' => $vehicle->id,
                    'staffs_id' => $staff
                ]);
            }

            $vehicle->staff()->save($staffs);
        }

        $request->session()->flash($this->message_success, ' Created Successfully.');
        return redirect()->route($this->base_route);
    }
2

2 Answers

3
votes

It seems you are creating many to many relationships, that is to say, a vehicle can belongs to many staffs, and a staff can have many vehicles. So, vehicle_staffs is a intermediate table (or pivot table) between vehicle model and staff model.

For Vehicle model, you should change the staff method to:

public function staff(){
    return $this->belongsToMany(Staff::class, 'vehicle_staffs', 'vehicles_id', 'staffs_id');
}

To update many to many relationships, you can attach the staff ids to vehicle:

$vehicle->staff()->attach($staffIds);

and the code change of your store function:

if ($request->has('staffs_id')) {
    $staffIds = $request->get('staffs_id');
    $vehicle->staff()->attach($staffIds);
}
0
votes

I don't know what version of Laravel you are using, so I assume you are on Laravel 5.x.

You should probably use saveMany() if you want to save more than one object. It takes a Collection or an array of Models as a parameter.

From the documentation:

If you need to save multiple related models, you may use the saveMany method:

$post = App\Post::find(1);

$post->comments()->saveMany([
    new App\Comment(['message' => 'A new comment.']),
    new App\Comment(['message' => 'Another comment.']),
]);