I am a beginner in laravel, in my form, In my blade, there are two selects, one simple select for selecting the office that does the work and the other select is multi select and for the cooperating offices, the latter can include several selections and be stored as an array in the table. office_id has a foreign key to the offices table. Everything works fine for simple select, but I have some problems for selecting the offices of my colleagues:
One is how to define the array column in the table, I defined it like this but I get an error:
$table->json('OtherOffices')->nullable();
$table->foreign('OtherOffices')->references('id')->on('offices');
Second, how to define in blade? I defined it like this:
<select name="otherOffices[]" id="otherOffices[]" multiple>
@foreach ($offices as $office)
<option value="{{ $office->id }}">
{{ $office->caption }}
</option>
@endforeach
</select>
Third, how to store the values in the table in the controller
public function create()
{
$tasks = Task::all();
$offices=Office::all();
return view('taskmanager.tasks.create', compact('tasks','offices'));
}
model :
public function Office(): BelongsTo
{
return $this->belongsTo(Office::class, 'office_id');
}
Please someone help me to understand the method of reading from table and writing to table for a multi select with foreign key
2
Answers
Simple solution is use implode & explode
You can store this as string into column and when you need to fetch the data from table use –
to convert the comma-separated string to array aging.
Otherwise use Morph –
https://laravel.com/docs/10.x/eloquent-factories#morph-to-relationships
Supposing that the task migration look like :
For json column, you can can cast it for better eloquent request. Your task model should look like :
Now, for all query, eloquent will convert the json data to array.
To add item in OtherOffices column, you can simply push it as array. A mathode like below can perform something like you want:
Hope it solve your problem.