Php 如何压缩此代码以从Laravel控制器向视图发送信息?
这是我在控制器中的编辑功能 我发送数据是为了在选择列表中显示。我知道雄辩的ORM方法列表,但问题是据我所知,它只能将属性名作为参数,而不能将方法(如Php 如何压缩此代码以从Laravel控制器向视图发送信息?,php,laravel,view,controller,eloquent,Php,Laravel,View,Controller,Eloquent,这是我在控制器中的编辑功能 我发送数据是为了在选择列表中显示。我知道雄辩的ORM方法列表,但问题是据我所知,它只能将属性名作为参数,而不能将方法(如name()和fullname()) 我如何优化它,我还能使用Eloquent吗?我唯一能想到的(除了使用Eloquent集合的映射功能外)是覆盖模型中的toArray方法以添加一些自定义属性 例如 这将允许您使用以下内容: $competition = $allCompetitions->fetch('fullname'); 尽管: 说到
name()
和fullname()
)
我如何优化它,我还能使用Eloquent吗?我唯一能想到的(除了使用Eloquent集合的映射功能外)是覆盖模型中的
toArray
方法以添加一些自定义属性
例如
这将允许您使用以下内容:
$competition = $allCompetitions->fetch('fullname');
尽管:
说到这一切,我认为更优雅的解决方案是只向视图提供整个竞争对象,并让渲染它们的循环(或其他)调用方法本身。你可以通过调整模型来做你想做的事情
竞争
<?php namespace App;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
class Competition extends Model
{
protected $appends = ['fullname'];
...
public function getFullnameAttribute()
{
return $this->name.' '.$this->venue;
}
}
如果视图文件中的模型方法与其他模型不相关,则可以调用它们。所以,如果name()&fullname()返回与此模型相关的结果,则可以在视图中使用此模型方法
@foreach (($allTeams as $t)
{{ $t->name() }}
@endforeach
当然,您必须将$allteams集合从控制器传递到视图,不幸的是,lists()不能使用自定义属性。为此,您需要一个集合。解决方案:
Competition::get()->列出('fullname','id')代码>@MichielvanderBlonk捕捉得好。我更新了答案以反映这一点。我可能也会限制select。
<?php namespace App;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
class Competition extends Model
{
protected $appends = ['fullname'];
...
public function getFullnameAttribute()
{
return $this->name.' '.$this->venue;
}
}
<?php namespace App;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
class Team extends Model
{
protected $appends = ['name'];
...
public function getNameAttribute()
{
return $this->city.' '.$this->teamName;
}
}
public function edit($id)
{
$game = Game::find($id);
$team = Team::get()->lists('id','name');
$competition = Competition::get()->lists('id','fullname');
return View::make('games.edit', compact('game', 'team', 'competition'));
}
@foreach (($allTeams as $t)
{{ $t->name() }}
@endforeach