rjruiz
2 months ago
452
3
Laravel

How to update a hasOne relationship?

Posted 2 months ago by rjruiz

I need to update a hasOne relationship in my update method I am trying the following and it is not working.

update method

                $piece = Piece::with('program')->findOrFail($id); 
            
                $program = $piece->program()->update($request->all());

                $piece = $program->piece()->update([
                    'denomination' => $request['denomination'],
                    'code'         => $request['code'],
                    'time'         => $request['time'],
                    'part_piece'   => $request['part_piece'],         
                    'gag_id'       => $request['number_gag'],         
                    'program_id'   => $program->id                     
                ]);                           
             
                $piece->syncTools($request->get('tools'));

I really need to update what I have in my store method

store method:

 $program = Program::create($request->all());
            
                $piece = $program->piece()->create([
                    'denomination' => $request['denomination'],
                    'code'         => $request['code'],
                    'time'         => $request['time'],
                    'part_piece'   => $request['part_piece'],         
                    'gag_id'       => $request['number_gag'],         
                    'program_id'   => $program->id                     
                ]);                           
             
                $piece->syncTools($request->get('tools'));


So how can I update what has already been saved before?

this is my piece model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Piece extends Model
{
    protected $fillable = [
        'program_id','gag_id', 'denomination', 'code', 'part_piece', 'time', 'observation'
    ];
    
    

    public function program()
    {
         return $this->belongsTo(Program::class);
    } 
    
    public function gag()
    {
        return $this->belongsTo(Gag::class);
    } 
       
    public function tools() 
    {        
        return $this->belongsToMany(Tool::class)->withTimestamps();
    }   
   
    public function syncTools($tools)
    {
       $toolsIds = collect($tools)->map(function($tool){
            return Tool::find($tool) ? $tool :Tool::create(['tool' => $tool])->id;
        });                

        return $this->tools()->sync($toolsIds);
    }    
}

this is my program model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Program extends Model
{
    protected $fillable = [
        'name_program','number_program','part_program'
    ]; 
   
    public function piece()
    {
        return $this->hasOne(Piece::class);
    }

  
}

Please sign in or create an account to participate in this conversation.