Method 1: Creating a helper
I generally create a helpers.php file in the app folder, and add it to autoload section of composer.json:
"autoload": {
"classmap": [
...
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/helpers.php" // Add this file
]
},
In helpers.php, add the function as follows:
function generateForumURL($name, $id)
{
// Using the url() helper, so you don't have to manually switch between
// localhost and the production website name
return url($name . "/" . $id);
}
Don't forget to run composer dump-autoload when you're done.
Another way would be to simply add a getUrlAttribute to the Forum model, that returns the URL:
class Forum extends Eloquent {
...
public function getUrlAttribute()
{
return url($this->name . '/' . $this->id);
}
}
You can now use $forum->url as a string anywhere you like.
Using the link template
You can save the template as a view (I normally do it in a partials folder) and include it wherever you need:
File views/forums/partials/link.blade.php:
@if(isset($forum))
<a href="{{ $forum->url }}">{{ $forum->name }}</a>
@endif
Include it in another views as follows:
@include('forums.partials.link', ['forum' => $forum])