简体   繁体   中英

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

In Blade I try {{ $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.

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

    #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
  • c904b27a-9b85-4782-a2de-deea0b9bbf18 returns 0
  • 53da0384-3a34-413c-bb73-b3e7b1d589ef returns 53
  • 86dd13d5-dd90-4734-9258-fba6742dd574 returns 86

Try with compact, but use it on the variable name (be careful with the syntax):

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:

(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. You can tell Laravel to make sure it is a string by casting it in the model :

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:

public $incrementing = false;

HTH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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