R
R
Roman Sarvarov2020-05-10 16:22:49
Laravel
Roman Sarvarov, 2020-05-10 16:22:49

How to get a link to show model?

I have Post and Page models.
At the moment, I get a URL to show some entity (show) based on the name of their route:

$postUrl = route('posts.show', $post, false);
$pageUrl = route('pages.show', $page, false);


But this is not very practical and I want to do it like this:
$postUrl = $post->url();
$pageUrl = $page->url();

// или так
$postUrl = $post->url;
$pageUrl = $page->url;


This can be done by adding the following function to the model:
// в модель post
public function url()
{
    return route('posts.show', $this, false);
}

// в модель page
public function url()
{
    return route('pages.show', $this, false);
}


But if I have hundreds of models? Is it possible to do something so as not to copy-paste this into each model, somehow, perhaps, to inherit from AbstractModel (or using a trait) and so that Laravel itself returns the correct name of the route?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Kim, 2020-05-15
@megakor

Referring to the router from the model method is such a pleasure.
Create a service, inject a router there, and generate a link there using the model class.

I
Ivan Ivanov, 2020-05-10
@maksim_fix

I don't think you have to render hundreds of links statically, well, you can add a url() method to the base controller (from which all controllers inherit), but you will have to work hard to make the names of the routes dynamic. As an option: give names to routes in the same style, then in this same url method take the current class name, remove the unnecessary Controller postfix, lowercase and form the url

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question