Laravel save relation from input

- 1 answer

Ad

I have the following relations:

Ticket Model:

public function status()
{
    return $this->belongsTo('App\Status');
}

Status Model:

public function tickets()
{
    return $this->hasMany('App\Ticket');
}

TicketController function create()

$statuses = Status::get()->lists('name', 'id');
return view('backend.tickets.create', compact('statuses'));

View create.blade.php

{!! Form::select('status', $statuses, null, ['class' => 'form-control'])  !!}

TicketController function store()

// Get the selected status from input and find the Status
   $status = Status::where('id', '=', $request['status'])->first();

// Associate status to ticket
    $ticket->status()->associate($status);

It does not work. In the database the status_id in my ticket table is always null.

Can you help me?

Thank you!

Ad

Answer

Ad

After the association, you should save the $ticket:

// Get the selected status from input and find the Status
$status = Status::where('id', '=', $request['status'])->first();
// or better
$status = Status::find($request['status']);

// Associate status to ticket
$ticket->status()->associate($status);

// Save the ticket
$ticket->save();
Ad
source: stackoverflow.com
Ad