2014-10-05 09:37
采纳率: 0%
浏览 1.0k


I'm very new to Laravel and php frameworks in general, so sorry if I miss anything basic. I've created a new model called Journey in my application which extends the standard Eloquent model. What I've noticed is that I'm using my Journey model in two different Controllers and I'm duplicating a bit of code because of it.

Essentially, what I'm doing is I'm taking the title of a Journey and I'm formatting it with a custom class to clean the title (convert to lowercase, add hyphens, remove whitespace, etc) so I can append it to my page URLs.

In one controller, I'm calling:

$journey = Journey::find($id);
$journey->cleanURL = Url::clean($journey['name']); // This creates a new element/property with a clean string

And in the other, I'm calling:

$journeys = Journey::all();
foreach ($journeys as $journey) {
    $journey->cleanURL = URL::clean($journey['name']);

It would be inappropriate to add a fixed field to my database with the cleaned URL because I may change the title (which the cleaned URL is based on) at any time and I'd like the URL to update automatically in this event. However, saying this, I'm repeating myself by calling Url::clean twice.

What I'd like to do is write a method or alter an existing method, so that when I call Journey::all() or Journey::find() or any query-based method, the URL field is already present and filled. I've tried looking through some of the Vendor/Eloquent files, but they just make me confused.

How would I go about doing this?

图片转代码服务由CSDN问答提供 功能建议

我对Laravel和php框架一般都很新,很抱歉,如果我错过任何基本的东西。 我在我的应用程序中创建了一个名为 Journey 的新模型,它扩展了标准的 Eloquent 模型。 我注意到的是我在两个不同的控制器中使用我的Journey模型,因为它我正在复制一些代码。

基本上,我正在做的是 我正在使用Journey的标题,我用自定义类格式化它以清理标题(转换为小写,添加连字符,删除空格等),以便我可以将其附加到我的页面URL。


  $ journey = Journey :: find($ id); 
 $ journey-> cleanURL  = Url :: clean($ journey ['name']);  //这创建了一个带有干净字符串的新元素/属性


  $ journeys = Journey :: all(); 
foreach($ journeys as $ journey){
 $ journey-> cleanURL = URL :: clean($ journey ['name']); 

使用已清理的URL向我的数据库添加固定字段是不合适的,因为我可以在任何地方更改标题(已清理的URL所基于的) 时间,我想要在此活动中自动更新的URL。 但是,这样说,我通过两次调用 Url :: clean 重复自己。

我想做的是写一个方法或改变一个方法 现有方法,以便当我调用 Journey :: all() Journey :: find()或任何基于查询的方法时,URL字段已经存在并填充 。 我已经尝试查看了一些 Vendor / Eloquent 文件,但它们让我感到困惑。


  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duandi4815 2014-10-05 09:44

    You can use accessor for this.

    Add to your Journey model the following function:

    public function getCleanUrlAttribute($value)
        return Url::clean($this->name);

    Now you will be able to use:

    $journey = Journey::find($id);
    echo $journey->clean_url;
    打赏 评论

相关推荐 更多相似问题