Back to Course |
How to Create Laravel Package: Step-by-Step Example

Load Blade Views

The next step is to load the same "It works" but from the Blade file, and we will see how to register our View in the Service Provider.

First, we create the file itself:

packages/laraveldaily/laravel-permission-editor/resources/views/roles/index.blade.php:

It works from Blade!

Then, we need to register the views to be loaded from that location. Again, as in other configurations, it's done in a Service Provider:

packages/laraveldaily/laravel-permission-editor/src/PermissionEditorServiceProvider.php:

class PermissionEditorServiceProvider extends ServiceProvider
{
public function boot()
{
Route::prefix('permission-editor')->group(function () {
$this->loadRoutesFrom(__DIR__ . '/../routes/web.php');
});
 
$this->loadViewsFrom(__DIR__ . '/../resources/views', 'permission-editor');
}
}

See that second parameter permission-editor? This is important for how to load the Views in the Controller, it's the Views namespace prefix.

Now, in the Controller, we load the View like this:

packages/laraveldaily/laravel-permission-editor/src/Http/Controllers/RoleController.php:

namespace Laraveldaily\LaravelPermissionEditor\Http\Controllers;
 
use Illuminate\Routing\Controller;
 
class RoleController extends Controller
{
 
public function index()
{
return view('permission-editor::roles.index');
}
 
}

See that permission-editor:: prefix? That's exactly the one that we registered just above.

Reload our route in the browser, and...

Laravel package - it works from Blade

In the same fashion, let's generate another Controller and the Routes for it.

packages/laraveldaily/laravel-permission-editor/src/Http/Controllers/PermissionController.php:

namespace Laraveldaily\LaravelPermissionEditor\Http\Controllers;
 
use Illuminate\Routing\Controller;
 
class PermissionController extends Controller
{
 
// Only this index for now: will show you why, in a minute
 
public function index()
{
return view('permission-editor::permissions.index');
}
 
}

And add the resourceful routes to the routes/web.php:

packages/laraveldaily/laravel-permission-editor/routes/web.php:

use Laraveldaily\LaravelPermissionEditor\Http\Controllers\RoleController;
use Laraveldaily\LaravelPermissionEditor\Http\Controllers\PermissionController;
use Illuminate\Support\Facades\Route;
 
Route::resource('roles', RoleController::class);
Route::resource('permissions', PermissionController::class);

Why do we need that "temporary empty" Controller now? Let me show you.