2

I have this code:

<td><a href="http://example.com/forum/{{ $forum->seo_name }}/{{ $forum->id }}">{{ $forum->name }}</a></td>

I wan't to use

{!! generateForumLink($forum->seo_name, $forum->id) !!}

how can I do it?

I have created simple function in controller:

public function generateForumURL($name, $id)
{
    return "http://localhost/".$name."/".$id;
}

how can I use it it template? Maybe exists better way to do this?

1 Answer 1

3

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.

Method 2: Defining an accessor

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])
Sign up to request clarification or add additional context in comments.

4 Comments

And how can I use it now? I'm tried {{ generateForumURL('test', 'test') }} and I'm got Call to undefined function generateForumURL()
Run composer dump-autoload.
Parse error: syntax error, unexpected 'public' (T_PUBLIC) in C:\myadmin\htdocs\app\helpers.php on line 2 line 2 : public function generateForumURL($name, $id) first is <?php
Oops, my bad. As the error clearly explains, remove the public from the helper function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.