
How to display pivot table column value in laravel
You can display additional column values from the pivot table using pivot->column_name after getting the data from the table using the with() method. To avoid errors you have to first define the belongsToMany() relationship using withPivot(‘column_name’).
-
Get pivot table column data using withPivot method
//Create projects() method with belongsToMany Relationship in - App\Models\User.php //App\Models\User.php public function projects(){ return $this->belongsToMany('App\Models\Project') ->withPivot('is_manager') ->withTimestamps(); } // app\Http\Controllers\<YourController>.php // Code inside controller's method $users = User::with('projects')->get(); return view('user.index', compact('users')); //Display pivot table column data in view file <!-- resources\views\user\index.blade.php --> @foreach($users as $user) @foreach($user->projects as $project) <p> Column value of is_manager - {{ $project->pivot->is_manager }} </p> @endforeach @endforeach
0You have to first create project model and table structure for projects table. After that you have to define belongsToMany relationship method in user model with method name projects(). Get projects data with users table data using with() method and return to view file and display in veiw file using pivot->is_manager.
To create project model and table structure of project table visit here - Create project table with model and migration .
If you want to get code snippets to create pivot table for projects and users tables you can visit here - create pivot table .
Random Code Snippet Queries: Laravel
- How to get selected categories on edit record with Select2
- Get previous date data in laravel
- How to get all route list
- Laravel change date format
- Get id of last inserted record in laravel
- How to get random string in Laravel
- The Pusher library requires the PHP cURL module. Please ensure it is installed
- How to restore deleted records in laravel
- Route [password.request] not defined
- Get Array of IDs from Eloquent Collection
- Argument 1 passed to Illuminate\Database\Query\Builder::cleanBindings() must be of the type array, null given
- How to get route method name in Laravel
- How to access the nth object from Laravel collection object ?
- Retrieve count of nested relationship data in Laravel
- Link storage folder in laravel 8
- Get last year created records in Laravel
- How to check column value of a record is null or not in laravel
- How to customize or Change validation error messages
- Create a record if not exist in laravel
- How to get specific columns using with method in laravel Eloquent relationship
- How to run a specific seeder class in laravel
- How to create projects method with belongstomany relationship in user model
- How to get all posts which contains comments in laravel
- Get laravel version
- Laravel append URI in route