title: Laravel : Setting dynamic routes based on access control list
body: <p>I am building <strong>REST API</strong> with <code>JWT</code> authentication and authorization with own logic. It's working perfectly. Now, I want to set the routes dynamically based on roles and permission. Suppose I have database structure like:</p>
  
  <p>Role:</p>
  
  <pre><code>id  |   name
  1   |  school
  2   | transport
  </code></pre>
  
  <p>Permissions:</p>
  
  <pre><code>id  |   name                   |  controller         | routes
  1   |  view-class-result       |  ApiController      | getClassResult
  2   |  view-student-result     |  ApiController      | studentResult
  3   |  download-student-result |  ApiController      | donwloadSchoolTemplate
  </code></pre>
  
  <p>Permission_role</p>
  
  <pre><code>role_id |  permission_id
  1            1
  1            2
  1            3
  </code></pre>
  
  <p>Now, I want to create routes according to roles and permission in database.</p>
  
  <p>Currently my routes seems like:</p>
  
  <pre><code>//All JWT authentication API goes here
  Route::group(['middleware' =&gt; 'jwt.auth'], function() {
     Route::get('user', 'ApiController@getAuthUser');
     Route::get('invalidate', 'ApiController@invalidate');
  
     //All authorized API goes here
     Route::group(['middleware' =&gt; 'ability:school,view-class-result,true'], function() {
         Route::post('classResult', 'ApiController@getClassResult');
     });
     Route::group(['middleware' =&gt; 'ability:school,view-student-result,true'], function() {
         Route::post('studentResult', 'ApiController@studentResult');
     });
     Route::group(['middleware' =&gt; 'ability:school,download-student-result,true'], function() {
         Route::post('getStudentExamResult', 'ApiController@downloadSchoolTemplate');
     });
  });
  </code></pre>
  
  <p>I don't want above routes to be hard coded. How can I get this routes from database. Something like below. But couldnot get idea how to do it.</p>
  
  <p>In routes file,</p>
  
  <pre><code>$a = User:all();
  foreach($a-&gt;roles as $value){
     foreach($value-&gt;permission as $val){
  
        Route::group(['middleware' =&gt; 'ability:{$value-&gt;name},{$val-&gt;name},true'], function() {
           Route::post('{$val-&gt;controller}', '{$val-&gt;controller}@{$val-&gt;method}');
        });
  
     }
  }
  </code></pre>
  
  <p>Thank you.</p>