我最近开始学习 Laravel,并且仍在尝试弄清楚。所以,在评判我之前请记住这一点:)
我正在尝试找到一种方法来重写它:
<a href="{{ url('clients/'. $campaign->client_id) }}">{{ App\Client::find($campaign->client_id)->name }}</a>
使用方法,因此我不必在 View 内执行 Client::find()
。
我尝试这样做:
private function getClientName($id)
{
$clientName = Client::find($id)->name;
return view('campaigns.index', compact('clientName'));
}
...在 Controller 中并调用了 View 内部的方法,但它不起作用,我现在想不到其他任何东西。
有什么建议吗?
最佳答案
使用您的 Controller 来执行此操作:
<?php
namespace App\Http\Controllers;
use Illuminate\Routing\Controller;
use App\Client;
class Clients extends Controller
{
public function index()
{
// You must have campaign here somehow
$campaign = whateverYouNeed();
// Then find the client and get the name
$clientName = Client::find($campaign->client_id)->name;
// And pass them both to your view
return view('clients', compact('campaign', 'clientName'))
}
}
然后在你的 Blade 中:
<a href="{{ url('clients/'. $campaign->client_id) }}">{{ $clientName }}</a>
在 Laravel 中执行此操作的另一个好方法是使用关系:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Campaign extends Model
{
/**
* Get the user that owns the phone.
*/
public function client()
{
return $this->belongsTo('App\Client');
}
}
然后您只需在 Blade 中使用它们即可:
<a href="{{ url('clients/'. $campaign->client_id) }}">{{ $campaign->client->name }}</a>
关于php - 如何在 Laravel 5.3 上的 Blade 文件内创建方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40920353/