Ad

Form Update Database Model Record's Relationship

- 1 answer

I want to know how to up date a model's relationship using a frontend form. I looked at the documents and found:

Alternatively you may set the relationship using the primary key, this is useful when working with HTML forms.

// Assign to author with ID of 3
$post->author = 3;

// Assign comments with IDs of 1, 2 and 3
$post->comments = [1, 2, 3];

$post->save();

the backend form to update the relationship works fine. This is my code and where I am getting ID as a value but it doesn't seem to affect the relationship field. Help would be great thanks!

    $project = new Projects(); 
    $project->name = Input::get('name');
    $project->price = Input::get('price');
    $project->work = Input::get('work');
    $project->client = Iput::get('work');
    $project->client = Input::get('client');
    $project->slug = $slug;
    $project->save();
    Flash::success('Estimate Added!');
    return Redirect::refresh();

This is the Pivot Table:

public function up()
    {
        Schema::create('brandon_invoice_ip', function($table)
        {
            $table->engine = 'InnoDB';
            $table->integer('invoices_id');
            $table->integer('projects_id');
            $table->primary(['invoices_id','projects_id']);
        });
    }

    public function down()
    {
        Schema::dropIfExists('brandon_invoice_ip');
    }
}

Here is the model relationship:

public $hasOne = [
        'client' => 'Brandon\Invoice\Models\Clients'
    ];

This is the front end form: The values are correct according to their ID.

<div class="uk-margin uk-first-column">
    <label class="uk-form-label" for="client">Client</label>
    <div class="uk-form-controls">
        <select class="uk-select" name="client">
          <option value="1">Brandon</option>
          <option value="2">Sanitary Ostomy System</option>
        </select>
    </div>
</div>

Image of the relationship in the builder.

Ad

Answer

I think you need to add belongsTo relationship instead of hasOne

public $belongsTo = [
    'client' => 'Brandon\Invoice\Models\Clients'
];
Ad
source: stackoverflow.com
Ad