1
votes

Am working on an application built using Laravel,, on the backend I have some eloquent Many to many relationship between 2 tables mainly roles and permissions respectively . There is also a pivot table called role_permission. I have created relationships in the models and in the controller am capturing the following values to create a permission: name, description , slug, role_id.

On the logic am storing name, description and slug in the permissions table while the role_id am storing in the pivot table (role_permission). This works fine. On the response am fetching all the permissions stored in the permission table and displaying back as a JSON object.

The problem is I want to fetch the role_id in the pivot table and append to each JSON object that was shown as a response.

Role Model

<?php

namespace Modules\API\Entities;
use Modules\API\Entities\Permission;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    protected $fillable = ['name' , 'slug' , 'description'];

    /**
     * A role has more than one permission
    */
    public function permissions(){
        return $this->belongsToMany(Permission::class , 'role_permission');
    }
}

Permission model

<?php

namespace Modules\API\Entities;
use Modules\API\Entities\Role;
use Illuminate\Database\Eloquent\Model;

class Permission extends Model
{
    protected $fillable = ['name' , 'slug' , 'description'];

     /**
     * A permission has more than one role
    */
    public function roles(){
        return $this->belongsToMany(Role::class , 'role_permission');
    }
}

Controller file (PermissionController.php)

<?php

namespace Modules\API\Http\Controllers;

use Carbon\Carbon;
use Modules\API\Common\helpers\GeneralHelper;
use Illuminate\Http\Request;
use Illuminate\Database\QueryException;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Validator;
use Modules\API\Entities\Permission;

class PermissionController extends Controller
{
    protected $requestTime;
    protected $reference_number;

    public function __construct()
    {
        $this->requestTime = Carbon::now()->toDateTimeString();
    }

    public function createPermission(Request $request) {

        $validator = Validator::make($request->all(), [ 
            'name' => 'required',
            "slug" => 'required',
        ]); 

        if ($validator->fails()) {          
            $response = GeneralHelper::failureException("Validation Failed", $validator->errors()->all(), Carbon::now()->toDateTimeString());
        }
        else{

            $name = $request->name;
            $description = isset($request->description) ? $request->description : null;
            $slug = isset($request->slug) ? $request->slug : null;
            $role = isset($request->role_id) ? $request->role_id : null;

            try{
                $permission = new Permission;
                $permission->name = $name;
                $permission->slug = $slug;
                $permission->description = $description;
                $permission->save();

                //Attach role to pivot table if permission is saved
                if($permission->save() && !is_null($role)){
                    $permission->roles()->attach($role);
                }

                //Select specific columns from permissions table and return a JSON object
                $permissions = Permission::select('id' , 'name', 'slug', 'description')->get()->toArray();

                $response = response()->json(GeneralHelper::success("Permision Successfully added", "data", $permissions , Carbon::now()->toDateTimeString()));
            } catch(QueryException $e){
                $response = response()->json(GeneralHelper::failureException("Database Exception", $e->getMessage() . " at LINE " . $e->getLine(), Carbon::now()->toDateTimeString()), Response::HTTP_INTERNAL_SERVER_ERROR);
            }
        }
        return $response;
   }
}

Sample response in POSTMAN after the above logic

{
    "request_time": "2019-09-03 07:54:54",
    "response_time": "2019-09-03 07:54:54",
    "status": "success",
    "message": "Permision Successfully added",
    "data": [
        {
            "id": 1,
            "name": "Create Post",
            "slug": "craete-post",
            "description": "mnmnmn"
        },
        {
            "id": 3,
            "name": "delete User",
            "slug": "del-user",
            "description": "mnmnmn"
        },
        {
            "id": 5,
            "name": "Create User",
            "slug": "create-user",
            "description": "mnmnmn"
        }
    ]
}

Updated response

{
    "request_time": "2019-09-03 09:16:46",
    "response_time": "2019-09-03 09:16:46",
    "status": "success",
    "message": "Permision Successfully added",
    "data": [
        {
            "id": 1,
            "name": "Kingston",
            "slug": "kingston-red-iuy",
            "description": "mnaskjas",
            "roles": [
                {
                    "id": 3,
                    "name": "Editor",
                    "slug": "editor",
                    "description": "Editor",
                    "created_at": "2019-09-02 06:37:08",
                    "updated_at": "2019-09-02 06:37:08",
                    "pivot": {
                        "permission_id": 9,
                        "role_id": 3
                    }
                }
            ]
        }
    ]
}`  

After using this command in the logic :

 $permissions = Permission::select('id' , 'name', 'slug', 'description')->with('roles')->get()->toArray();
1

1 Answers

1
votes

Try changing:

$permissions = Permission::select('id' , 'name', 'slug', 'description')->get()->toArray();

into:

$permissions = Permission::select('id' , 'name', 'slug', 'description')->with('roles')->get()->toArray();

$mappedPermissions = array_map(function ($permission) { 
    $permission['role_id'] = data_get($permission, '0.pivot.role_id');

    unset($permission['roles']); 

    return $permission; 
}, $permissions);

// Then use the $mappedPermissions from here on.