cant display all result from 2 table join with pivot table

Viewed 56

I have managed to join between 2 tables by using 1 pivot table(I have to), but I cant loop my way to get all of joined result, Bellow are:

Models App.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class App extends Model
{
    protected $table = 'bas_app';
    public $timestamps = false;
    protected $fillable = ['id','app_name','app_type','description','menu_name','menu_url','menu_parent_id'];

    public function roles()
    {
        return $this->belongsToMany(Role::class,'bas_role_app','app_id','role_id');
    }

}

Role.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    //
    protected $table = 'bas_role';
    protected $fillable = ['name','remark'];

    public function users()
    {
        return $this->belongsToMany('App\User','bas_user_role','role_id','user_id')
        ->withPivot('id');
    }

    public function apps()
    {
    //     return $this->belongsToMany(App::class,'bas_role_app','role_id','app_id')
    //     ->withPivot('id','priv_access','priv_insert','priv_delete',
    // 'priv_update','priv_export','priv_print','app_name');
    return $this->belongsToMany(App::class,'bas_role_app','role_id','app_id');
    }

}

RoleApp.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;

class RoleApp extends Pivot
{
    //
    public $timestamps = false;
    protected $table = 'bas_role_app';
    protected $fillable = ['role_id','app_id','app_name'];

    public function b_app() {
        return $this->belongsToMany(App::class);
    }

    public function b_role() {
        return $this->belongsToMany(Role::class);
    }
}

Controller RoleAppController.php

    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Validator;
    use Illuminate\Support\Facades\Auth;
    use Carbon\Carbon;
    use Illuminate\Support\Facades\Route;
    use App\User;
    use App\Role;
    use App\App;
    use App\ActivityLog;
    use App\RoleApp;
    use Illuminate\Support\Facades\Input;
    use DB;
    
    class RoleAppController extends Controller
    {
        public function __construct()
        {
            $this->middleware('auth');
        }
    
        public function display(Request $request)
        {
             $routes =  preg_match('/([a-z]*)@([a-z]*)/i', Route::currentRouteAction(), $matches);
             $routes = $matches[0];
             $action = $matches[2];
    
            if (Auth::check()) {
                DB::beginTransaction();
    
                try {
                $id = Auth::id();
                $profile_data = User::find($id);
                $RoleApp = Role::all();
            //$RoleApp->apps;
          //  dd($RoleApp);
          
    
                     ActivityLog::create([
    
                         'inserted_date' => Carbon::now()->TimeZone('asia/jakarta'),
                         'username' => $profile_data->username,
                         'application' => $routes,
                         'creator' => "System",
                         'ip_user' => $request->ip(),
                         'action' => $action,
                       'description' => "admin is looking at the role and application management",
                         'user_agent' => $request->server('HTTP_USER_AGENT')
                     ]);
    
                     DB::commit();
                 } catch (\Exception $ex) {
                     DB::rollback();
                 return response()->json(['error' => $ex->getMessage()], 500);
    
                 }
              //  return view('RoleApp', ['RoleApp' => $RoleApp]);
               return view('RoleApp', ['RoleApp' => $RoleApp]);
             } else {
                 return view("login");
             }
        }
}

View RoleApp.blade.php

@extends('layouts.master')
@section('title','Display-RoleApp')
@section('content')


<div class="container mt-5">
    <div class="row">
        <div class="col-12">
            @if($errors->any())
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                {{ implode(', ', $errors->all(':message')) }}
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            @endif
            <div class="float-right mb-5">
                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">
                    Insert Role App
                </button>
            </div>




   <!-- Modal -->
   <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLongTitle">Insert User</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form action="/roleapp/create" method="POST">
                    {{ csrf_field() }}

                    <div class="form-group">
                        <label for="role_name">role name:</label>
                        <input type="text" class="form-control" name="role_name">
                    </div>

                    <div class="form-group">
                        <label for="app_name">app name:</label>
                        <input type="text" class="form-control" name="app_name">
                    </div>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Submit</button>
            </div>
            </form>
        </div>
    </div>
</div>


                <div class="table-responsive m-b-40">
            <table id="roleapp-table" class="table table-striped">
                <thead>
                    <tr>
                        <th scope="col">Role Name</th>
                        <th scope="col">App Name</th>
                        <th scope="col" class="text-center">Action</th>
                        <th scope="col" class="text-center">Action</th>
                    </tr>
                </thead>
                <tbody id="dynamic-row">
                    @foreach ($RoleApp->apps as $rp)
                    <tr>

                        <td>{{$RoleApp->name}}</td>
                        <td>{{$rp->app_name}}</td>

                        <td class="text-center">
                            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modal_ubah_{{$rp->id}}">Edit</button>
                        </td>
                        <td class="text-center">
                            <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#modal_hapus_{{$rp->id}}">Hapus</button>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

<script type="text/javascript">
    var row = 0;
    $(document).ready(function() {
        $('#user-table').DataTable({
            select: true,
            retrieve: true,
            "order": [
                [0, "desc"]
            ],
            "lengthMenu": [
                [20, 50, 100, 500, 1000, -1],
                [20, 50, 100, 500, 1000, "All"]
            ],
            "language": {
                "paginate": {
                    "next": ">",
                    "previous": "<"
                }
            }
        });
    });
    $('#user-table thead tr').clone(true).appendTo('#user-table thead');
    $('#user-table thead tr:eq(1) th').each(function(i) {
        if (row < 7) {
            var title = $(this).text();
            $(this).html('<input type="text" placeholder="Search ' + title + '" />');
        } else {
            $(this).html('');
        }
        row++;

        $('input', this).on('keyup change', function() {
            if (table.column(i).search() !== this.value) {
                table
                    .column(i)
                    .search(this.value)
                    .draw();
            }
        });
    });
</script>

@endsection

Any suggestion? I have tried various way and its still not working. I suspect that something is wrong in

$RoleApp = Role::all();

or

  @foreach ($RoleApp->apps as $rp)
                        <tr>
    
                            <td>{{$RoleApp->name}}</td>
                            <td>{{$rp->app_name}}</td>
    
                            <td class="text-center">
                                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modal_ubah_{{$rp->id}}">Edit</button>
                            </td>
                            <td class="text-center">
                                <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#modal_hapus_{{$rp->id}}">Hapus</button>
                            </td>
                        </tr>
                        @endforeach

if I try it with $RoleApp = Role::find(2); it will still work, but when i use get or all, it wont work.

1 Answers

without eager loading.

$roles = Role::all();

with eager loading

$roles = Role::with('apps')->get();

$roles is a collection of model instances of Role Model. You can't access a property or relation of a model, on a collection. That is the reason it works when you use find(given model instance), and doesn't work for all or get(give collection).

You need to iterate over the collection and then access the relation like this.

foreach($roles as $role){
    // name of each role.
    $role->name;

   
    foreach($role->apps as $app){
       // name of each app associated with the $role.
       $app->name;
    }
}
Related