Matt E. Matt E. - 3 days ago 4
PHP Question

How to create a method inside of the blade file on Laravel 5.3

I recently started learning Laravel and I am still trying to figure it out. So, please bear in mind this before judging me :)

I am trying to find a way to rewrite this:

<a href="{{ url('clients/'. $campaign->client_id) }}">{{ App\Client::find($campaign->client_id)->name }}</a>


with a method, so I wouldn't have to do
Client::find()
inside of the view.

I tried doing this:

private function getClientName($id)
{
$clientName = Client::find($id)->name;
return view('campaigns.index', compact('clientName'));
}


... in the controller and called the method inside of the view, but it didn't work, and I can't think of anything else right now.

Any suggestions? Thanks!

Answer

You can create helper files using composer. In order to make it work, you will need to autoload it within your composer.json file. You will need to add the "files" along with a path to the helper file you've created.

"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "helpers/general.php"
    ]
},

Once you've done this, you should be able to add a regular function to your helper file. It might look something like this.

<?php 

function getClientName($id){
    // Add code to get client name
}

You could then access from your blade like this.

<a href="{{ url('clients/'. $campaign->client_id) }}">{{ getClientName($campaign->client_id) }}</a>

What I've suggested should work, but the more Laravel way of doing it would be to properly build your relationship so you can do something like the following.

<a href="{{ url('clients/'. $campaign->client->id) }}">{{ $campaign->client->name }}</a>

I'd need to see your database structure in order to suggest which type of relationship you'd need, but you should be able to find what you're looking for in the documentation. https://laravel.com/docs/5.3/eloquent-relationships.

Edit: Since you seem to have client_id in your campaign table, that means your campaign likely "BelongsTo" a client. A client on the other hand has "HasMany" campaigns. This terminology might help you with the documentation.

Comments