Home > Net >  Retrieve and Create Data in many to many relationship in Laravel 8
Retrieve and Create Data in many to many relationship in Laravel 8

Time:02-19

I want to create a user through a form. In the form I will select the user type accordingly the user will be created and it will be saved in the database. I can do everything but I don't understand how to show user role in select menu with controller and how to create the user. I have three separate tables. One is for the user, the other is for the role and the other is the user role. Please help me

My User Models

class User extends Model
{
    public function user(){
        return $this->belongsToMany(Role::class, 'roles_users');
    }
}

my roles Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    public function user(){
        return $this->belongsToMany(User::class, 'roles_users');
    }
}

Controller

class FormController extends Controller
{
    public function index(){
        $user = User::find(1);  
 
        $role_ids = [1, 2];
        $user->roles()->attach($role_ids);
    }
}

this is my view

<form action="{{route('store.data')}}" method="post">
    @csrf
    <label for="">User Type</label>
    <select name="usertype"></select>
    <option value="">Select Usertype</option>
    @foreach($data as $user)
    <option value="{{$user->id}}">{{$user->name}}</option>
    @endforeach

    <label for="">Username</label>
    <input type="text" name="username">

    <button type="submit">Add User</button>


</form>

CodePudding user response:

Are you wanted 1 user have 1 role, or 1 user have many roles?

CodePudding user response:

First your should add role_id in your user table, then use hasOne Relationship function.

In your User Model, add this

public function role()
{
    return $this->hasOne('App\Models\Role');
}

Then, in your Role Model, add this

public function user()
    {
        return $this->belongsTo('App\Models\User', 'role_id');
    }

Then you can call function on your controller

$user = User::with('role')->get();

Don't forget to add use App\Models\ModelName;on your Controller in case you wanted to use some model so you can declare Modelname::class instead of Model path

  • Related