8 months ago

Shared methods in Models

Posted 8 months ago by oliverbusk

I have a blade file, that represents a menu bar. And inside the menu bar, I call a method called path() as below:


<li class="nav-item">
     <a class="nav-link" href="{{ $stream->path(['documents']) }}">Documents</a>

Now the path method, simple build up a link with the correct path, starting from my /streams url.

    public function path($subpaths = [])
        $path = '';
        foreach ($subpaths as $subpath) {
            $path .= '/' . $subpath;

        return '/streams/' . $this->token . $path;

So for example, {{ $stream->path(['documents']) }} would produce: /streams/documents

Now this works perfectly.

However, as my "subpaths" will ultimately reference other controllers and thus models than StreamsController and Stream, my path method no longer works, without me typehinting the Stream $stream variable in my controller.

For example, inside my StreamDocumentsController.php, I have to do this:

   public function index(Stream $stream, Document $document)
        return view('streams.documents.index', compact('stream','$document'));

Now what is the correct way to share the path() method accross my models, so I don't have to typehint the Stream model in all my controllers`

Can I create some sort of class/trait/interface that can be used accross my models, so they can all inherit the path() method?

Please sign in or create an account to participate in this conversation.