You must use laravel eloquent to create a connection between your model. For example: If you have 2 tables (roles, users), and the relationship between them is many for many, you need to create a Role and User for the model, and then write the code below in the Role model: users of public functions () {return $ this- > ownaToMany ('App / User'); }
and in the user model:
public function roles() { return $this->belongsToMany('App/Role') }
after that create a new migration and put the name of the table role_user and put the code below:
public function up() { Schema::create('category_post', function (Blueprint $table){ $table->increments('id')->unsigned(); $table->integer('post_id')->unsigned()->index(); $table->integer('category_id')->unsigned()->index(); $table->timestamps(); $table->foreign('category_id') ->references('id')->on('categories') ->onUpdate('cascade') ->onDelete('cascade');$table->foreign('post_id') ->references('id')->on('posts') ->onUpdate('cascade') ->onDelete('cascade'); }); }
Save it and run php artisan migrate. Its over, and now you have a lot of relationships. After all this, to get the forexample request for the associated role to the user, add your User and Role model to your controller, do like this:
public function edit($id){ $user=User::whereId($id)->firstOrFail(); $roles=Role::all() $selectedRole=$user->roles()->lists('id')->toArray(); return view('your page view',compact($user,$roles,$selectedRole)); }
and to show the selected roles in your view, write:
<select id="role" name="role[]" multiple> @foreach($roles as $role) <option value="{!! $role->id !!}" @if(in_array($role->id, $selectedRoles)) selected="selected" @endif > {!! $role->display_name !!} </option> @endforeach </select>
Done.
source share