代码之家  ›  专栏  ›  技术社区  ›  Cicharito

substr方法的简单拉维公共函数(if/else)

  •  0
  • Cicharito  · 技术社区  · 7 年前

    我的页面中有一个表,共有6列,最后一个名为Notes(Description)的表需要一些帮助。在这里,我使用工具提示来显示上面的描述,因为文本通常很长,对于列文本,我使用substr($item->notes,0,15)仅捕捉前15个字母。

    现在,我要做的是在我的模型中创建一个函数,为我提供下一个行为:如果项目有描述,那么显示substr($item->notes,0,15),否则只显示“N/a”。

    以下是我的条目:

    <td class="text-right" data-toggle="tooltip" data-placement="top" data-html="true" title="{{ $item->notes ? $item->notes : 'N/A'  }}">{{ substr($item->notes, 0, 15) }}</td>
    
    4 回复  |  直到 7 年前
        1
  •  1
  •   Lars Mertens    7 年前

    https://laravel.com/docs/5.5/eloquent-mutators#accessors-and-mutators

    要定义访问器,请创建 getFooAttribute 哪里 是您希望访问的列的“studly”大小写名称。 在本例中,我们将为 名字 属性当出现以下情况时,Eloquent将自动调用访问者: 正在尝试检索 属性:

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class User extends Model
    {
        /**
         * Get the user's first name.
         *
         * @param  string  $value
         * @return string
         */
        public function getFirstNameAttribute($value)
        {
            return ucfirst($value);
        }
    }
    

    在你的情况下,这会导致类似的结果

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Item extends Model
    {
        protected $fillable = ['notes']; // just for this demo
    
        public function getNotesAttribute($value)
        {
            if (!empty($value)) {
                return substr($value, 0, 15);
            } else{
                return 'N/A';
            }
        }
    }
    
        2
  •  0
  •   Rusben Guzman    7 年前

    使用laravel的helper函数,在这种情况下,str_limit()将为您提供服务,例如:

    <td class="text-right" data-toggle="tooltip" data-placement="top" data-html="true" title="{{ $item->notes ? $item->notes : 'N/A'  }}">
        {{ str_limit($item->notes, 15) }}
    </td>
    

    此外,laravel还有许多更有用的功能,您可以在文档中看到它们:

    https://laravel.com/docs/5.1/helpers#method-str-limit

    https://laravel.com/docs/5.1/helpers

    现在,如果您需要在这里创建自己的函数,请解释一种方法:

    https://laracasts.com/discuss/channels/general-discussion/best-practices-for-custom-helpers-on-laravel-5?page=1

        3
  •  0
  •   Stanley Umeanozie    7 年前

    如果您只想做$item->注释在视图中,无需每次编写条件,您将必须在模型中使用访问器。

    在这里,我假设“notes”是您的despription财产的名称。修改它以满足您的需要。

    public function getNotesAttribute($value) {
          if (!empty($value)) {
            return substr($value, 0, 15);
          } else{
            return 'N/A';
          }
    }
    
        4
  •  -1
  •   Roots    7 年前

    <td class="text-right" data-toggle="tooltip" data-placement="top" data-html="true" title="{{ $item->notes ? $item->notes : 'N/A'  }}">{{ substr($item->notes, 0, 15) ? substr($item->notes, 0, 15) : 'N/A' }}</td>