glhd / gretel

Laravel breadcrumbs right out of a fairy tale
MIT License
243 stars 16 forks source link

Convenient way to export breadcrumbs as a collection #1

Closed innocenzi closed 3 years ago

innocenzi commented 3 years ago

I'm looking for a solution to handle breadcrumbs for an application written with Inertia. This package seems like a good candidate, I like the syntax macro'd to the routes.

My issue is that this package was made with Blade in mind, thus it doesn't offer a convenient way to export the breadcrumbs as a collection. I need this feature because with Inertia, you pass whatever the front-end need to a middleware, and work with it in the front-end.

My current workaround is the following:

// Middleware/ShareNavigation.php
public function handle($request, \Closure $next)
{
    inertia()->share('navigation', [
        'breadcrumbs' => app(\Glhd\Gretel\View\Components\Breadcrumbs)->breadcrumbs,
        // other stuff
    ]);

    return $next($request);
}

A facade would be better:

Breadcrumbs::render();
// or something like
Breadcrumbs::asCollection();
inxilpro commented 3 years ago

Sure, that makes sense. Would you want all the breadcrumbs or just the current route?

innocenzi commented 3 years ago

I think both options for different use cases would be nice, but in my current case I just need the behavior of the described workaround, so I think that means "just the current route". For instance:

Route::get('/users/{user}/edit', [Administration\Controllers\UsersController::class, 'edit'])
    ->withTrashed()
    ->name('users.edit')
    ->breadcrumb(fn (User $user) => $user->full_name, 'admin.users');

In this case, I get two parts: one with is_current_page set to true and with a title corresponding to $user->full_name, and the parent corresponding to the named route admin.users.

inxilpro commented 3 years ago

OK. I'm about to publish 1.3.0 which will do this automatically for you. If you have Inertia installed, you'll just have a breadcrumbs value shared with Inertia that looks like this:

const breadcrumbs = [
  {
    title: 'Home',
    url: 'https://www.yourapp.com',
    is_current_page: false,
  }, {
    title: 'Users',
    url: 'https://www.yourapp.com/users',
    is_current_page: false,
  }, {
    title: 'Add a User',
    url: 'https://www.yourapp.com/users/create',
    is_current_page: true,
  }
];

You can also get the current breadcrumbs off the Route facade, by calling Route::breadcrumbs(). This is an instance of RequestBreadcrumbs which has toCollection() and toArray and toJson methods.

inxilpro commented 3 years ago

Take a look at 1.3.0 and feel free to reopen this issue if that doesn't cover your use case.

innocenzi commented 3 years ago

Dude, this is way better than my expectations. Thanks a lot!