[英]Laravel Custom Route Model Binding
我有以下设置:
routes.php文件
Route::get('{page?}', [
'uses'=>'PageController@getPage',
'as'=>'page'
])->where('page', '(.*)?');
RouteServiceProvider.php
$router->bind('page', function($value, $route)
{
if($value == "/"){ $value = "home"; };
$explodedPage = explode("/",$value);
$page = Page::findBySlug(last($explodedPage));
if(!isset($page)){
\App::abort(404);
}
$ancestors = $page->ancestorsAndSelf()->get();
$sections=array();
foreach($ancestors as $ancestor)
{
$sections[]=$ancestor->slug;
}
if(implode("/",$sections)==$value){
return $page;
}else{
return $page;
//Else Redirect
}
});
page.php文件
use Baum\Node;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use URL;
use Venturecraft\Revisionable\RevisionableTrait;
use Illuminate\Database\Eloquent\SoftDeletes;
use Cviebrock\EloquentSluggable\SluggableInterface;
use Cviebrock\EloquentSluggable\SluggableTrait;
class Page extends Node implements SluggableInterface
{
use RevisionableTrait, SoftDeletes, SluggableTrait;
protected $sluggable = array(
'build_from' => 'title',
'save_to' => 'slug',
);
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['title', 'description', 'content', 'owner_id', 'system', 'status'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['parent_id','lft','rgt','depth'];
/**
* The attributes excluded from revision
*
* @var array
*/
protected $dontKeepRevisionOf = ['updater_id','parent_id','lft','rgt','depth'];
}
URLS看起来像这样:
localhost/ (uses pre-defined slug)
localhost/page-slug
localhost/parent-slug/page-slug
localhost/parent-parent-slug/parent-slug/page-slug
Etc...
检索页面效果很好; 但是我的问题是关于生成URL
{{URL::route('page',$page)}}
简单生成,localhost / page-id
我知道我可以做:
{{URL::route('page',['page'=>$page->generateURLString()])}}
但是,如果可能的话,我宁愿使用这种清洁剂。 有人有什么建议吗?
如您所说,您可以执行{{URL::route('page',['page'=>$page->generateURLString()])}}
因为route('page',$page)
将返回模式名称。
然后,我的建议是,当您需要一些清洁剂时,可以创建一个扩展Route类的自定义函数,或者只是将其声明为常规函数:
public function page($bind){
return route('page', ['page' => $bind]);
}
然后做:
{{ page($page->generateURLString()) }}
从版本5开始,您现在可以在Model
(通过UrlRoutable
)使用getRouteKey()
,该方法可用于返回自定义路由键。 就像是:
class Page extends Node implements SluggableInterface
{
//......
public function getRouteKey() {
return $this->generateURLString();
}
}
使{{ route('page', $page) }}
表现理想。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.