WHat is the best way to implement a view layer logic?

msamgan profile image Mohd Samgan Khan ・1 min read

What's the best way to implement a view layer login like a graph or something which is to be used on more than one place in laravel?


markdown guide

Would you further clarify what exactly are you trying to do? On the surface, I feel like you're looking for reusable components in your Blade templates. This could be cleanly done with components and slots. Or perhaps you're looking for something else?


Thanks for the response, John. Components and slots do the work but not quite what I have in mind. I am looking more like Cell from CakePHP.


Sounds like implementing \Illuminate\Contracts\Support\Rend... interface would be the most similar. This interface only has one method render(). When you pass this object to the view and output like a normal variable {{ $yourVariable }}, it would render whatever you returned in your render method.

thanks, Dainius.
BTW do you have any working example of the same?

Actually, you should probably use Htmlable interface, if you want to return html from your 'cell'.

Well lets take a look at this example from CakePHP

namespace App\View\Cell;

use Cake\View\Cell;

class InboxCell extends Cell

    public function display()
        $unread = $this->Messages->find('unread');
        $this->set('unread_count', $unread->count());

What this does, is basically counts how many unread messages there are, and returns a different html template. Now, I don't have messages model in my app, so let's say I want to return a count of how many users my app has. Lets call it UsersCountCell for now.

In my app folder, I create UsersCountCell.php with the following content,


namespace App;

use Illuminate\Contracts\Support\Htmlable;

class UsersCountCell implements Htmlable
    public function toHtml()
        $userCount = User::count();

        return view('cells.users_count', [
            'count' => $userCount,
There are {{ $count }} users

You then use it like this:

Route::get('/', function () {
    return view('welcome', [
        'cell' => new \App\UsersCountCell(),
    The following will come from htmlable: {{ $cell}}

This will properly render the html from your users_count.blade.php, whereas previously mentioned renderable would require you to render it like this {!! $cell !!}. You can actually use both interfaces, and then in your toHtml() method just return $this->render();

Let me know if you need any more information, I might write a blog post about this 🤔

thanks a lot.
I guess I can work on this. thanks a lot and I will be waiting for the article...