如何在Laravel中为模型添加自定义字段?

如何在Laravel中为模型添加自定义字段?

问题描述:

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?

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

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

在一个控制器中,我正在呼叫: p>

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

另一方面,我正在调用: p>

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

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

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

我将如何做到这一点? p > div>

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;