简体   繁体   English

如何防止Laravel Blade剥离字母数字字符串?

[英]How do I keep Laravel Blade from stripping out alphanumeric strings?

I have an ID field on my model that consists of alphanumeric strings like 6f7fb019-1a57-4beb-916a-8605868c19a2 我的模型上有一个ID字段,其中包含6f7fb019-1a57-4beb-916a-8605868c19a2等字母数字字符串

In Blade I try {{ $var->ID }} 在Blade中,我尝试{{ $var->ID }}

Blade strips out most of this string, even when I wrap it in {!! !!} 即使我将其包裹在{!! !!} {!! !!}

However when I wrap the literal string in double quotes like {{ " 6f7fb019-1a57-4beb-916a-8605868c19a2" }} all is well. 但是,当我将文字字符串用双引号括起来,例如{{ " 6f7fb019-1a57-4beb-916a-8605868c19a2" }}一切都很好。

blade template code: 刀片模板代码:

    @foreach($work_requests as $work_request)
        <tr>
            <th scope="row">{{$work_request->ID}}</th>
            <td>{{$work_request->STATUS}}</td>
            <td>{{$work_request->created}}</td>
        </tr>
    @endforeach

raw model from dd 来自dd原始模型

    #attributes: array:4 [▼
      "ID" => "6f7fb019-1a57-4beb-916a-8605868c19a2"
      "JSON" => ""
      "STATUS" => " [ CONFIDENTIAL ] "
      "created" => 1550623543
    ]

from controller: 来自控制器:

public function index()
{
    $work_requests = WorkRequest::orderby('created','desc')->paginate(25);
    dd($work_requests);
    return view('workrequests.index')->with('work_requests',$work_requests);
}

FURTHER EXPLANATION 进一步说明

So for these values I get the corresponding result printed: 因此,对于这些值,我得到了相应的打印结果:

  • 6f7fb019-1a57-4beb-916a-8605868c19a2 returns 6 6f7fb019-1a57-4beb-916a-8605868c19a2返回6
  • c904b27a-9b85-4782-a2de-deea0b9bbf18 returns 0 c904b27a-9b85-4782-a2de-deea0b9bbf18返回0
  • 53da0384-3a34-413c-bb73-b3e7b1d589ef returns 53 53da0384-3a34-413c-bb73-b3e7b1d589ef返回53
  • 86dd13d5-dd90-4734-9258-fba6742dd574 returns 86 86dd13d5-dd90-4734-9258-fba6742dd574返回86

Try with compact, but use it on the variable name (be careful with the syntax): 尝试使用compact,但是在变量名上使用它(请注意语法):

return view('workrequests.index', compact ('work_requests'));

For the numbers coming out of blade - this is possibly because, by default, the primary key in Laravel is cast as int like: 对于从刀片出来的数字-这可能是因为默认情况下,Laravel中的主键被强制转换为int例如:

(int) "6f7fb019-1a57-4beb-916a-8605868c19a2" == 6

It is still a string, but if you call it via the model's id, it goes through the __get() method, and becomes an int. 它仍然是一个字符串,但是如果通过模型的ID调用它,它将通过__get()方法,并成为一个int。 You can tell Laravel to make sure it is a string by casting it in the model : 您可以通过在模型中强制转换来告诉Laravel确保它是一个字符串:

protected $casts = ['id' => 'string'] ; protected $casts = ['id' => 'string'] ;

You can also go directly to the id function and tell Laravel not to increment, which might help more precisely in your case than the $casts variable: 您也可以直接转到id函数,并告诉Laravel不要递增,这可能比$casts变量更精确地帮助您:

public $incrementing = false;

HTH 高温超导

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM