Рабочий образец (протестирован):
Миграция: 2020_06_16_000000_create_employees_table. php
class CreateEmployeesTable extends Migration
{
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('employees');
}
}
Миграция: 2020_06_16_000000_create_teams_table. php
class CreateTeamsTable extends Migration
{
public function up()
{
Schema::create('teams', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('teams');
}
}
Миграция: 2020_06_16_000000_create_employee_team_table. php
class CreateEmployeeTeamTable extends Migration
{
public function up()
{
Schema::create('employee_team', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('employee_id')->nullable();
$table->foreign('employee_id')->references('id')->on('employees')->onDelete('cascade');
$table->unsignedBigInteger('team_id')->nullable();
$table->foreign('team_id')->references('id')->on('teams')->onDelete('cascade');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('employee_team');
}
}
Модель: Сотрудник. php
class Employee extends Model
{
public function teams()
{
return $this->belongsToMany('App\Team');
}
}
Модель: Team. php
class Team extends Model
{
public function employees()
{
return $this->belongsToMany('App\Employee');
}
}
Маршруты: routes / web. php:
Route::get('/select_team/{id?}', 'EmployeeController@select_team')->name('employee.select_team');
Route::post('/save_teams/{id?}', 'EmployeeController@save_teams')->name('employee.save_teams');
Контроллер: EmployeeController. php
use Illuminate\Http\Request;
use App\Team;
use App\Employee;
class EmployeeController extends Controller
{
public function select_team($employee_id){
return view('select_team', ['tdropdown'=>Team::all(), 'employee'=>Employee::find($employee_id)]);
}
public function save_teams(Request $request, $employee_id){
$employee = Employee::find($employee_id);
foreach ($request->namedropdown as $team_id){
$employee->teams()->attach($team_id);
}
return redirect()->route('employee.index')->with('success','Data Added');
}
}
Blade: select_team.blade. php
<!DOCTYPE html>
<form action="/save_teams/{{$employee->id}}" method="post">
@csrf
<select name="namedropdown[]" id="namedropdown" class="selectpicker" multiple data-live-search="true">
<option value="" disabled selected>Nothing selected</option>
@foreach ($tdropdown as $tdrop)
<option value="{{$tdrop->id}}">{{$tdrop->name}}</option>
@endforeach
</select>
<button>Submit</button>
</form>
</html>
Думаю, это хороший пример, который может дать вам представление.