Home > front end >  Eloquent relationship update appropriate database fields in Laravel
Eloquent relationship update appropriate database fields in Laravel

Time:09-10

I have BelongsTo model between 3 database (Admins, vendors, and vendor_business_table) table in Laravel. Trying to save the data which comes from HTML form in appropriate database field. My Admin Model looks like below:

class Admin extends Authenticatable
{
    use HasFactory;
    protected $guard = 'admin';

    public function getVendorDetails(){
        return $this->belongsTo(Vendor::class, 'vendor_id','vendor_id');
    }

    public function getVendorBusinessDetails(){
        return $this->belongsTo(VendorBusinessDetails::class, 'vendor_id','vendor_id');
    }

}

Once all the data is sent from the form I am trying to catch and save the fields. We have only id field is foreign key.

public function editVendorsDetails(Request $request,$id){
               
                if($request->isMethod('post')){
                $data = $request->all();
                   $myModel = Admin::with('getVendorDetails')->find($id);
                   $myModel->getVendorDetails->fill($data);
                   $myModel->getVendorDetails->save();

Once I save the form nothing is changed. Am I missing something here? Your help would be highly appreciated.

CodePudding user response:

Would you please replace your code with this code in editVendorDetails()

if($request->isMethod('post')){
     $data = $request->all();
     $myModel = Admin::with('getVendorDetails')->find($id);
     $myModel->getVendorDetails()->create($data);
 }

CodePudding user response:

// fill this array which field you want to store like name
protected $fillable = ['name'];

or

protected $guarded = [];

Have a look at is Mass Assignment Documantation.

  • Related