0

I have a table, from an old database, where the primary key is a string. When I print it on the screen, it is printed like an integer. Eg. if the key is 8-001abc, on the screen I have 8.

This is my code: model

protected $table = 'mytable';
public $primaryKey = 'mykey';
public $incrementing = false;
protected $casts = [
    'mykey' => 'string'
];

controller

$item = MyModel::where('somefield', '=', 0)->get();
return view('mymodel.index', compact('item'));

view

@foreach($item as $rowitem)
   <p>{{ $rowitem->mykey }}</p>
@endforeach

any idea? thank you!

lorenzo
  • 187
  • 2
  • 8
  • should be able to just use {{ (string)$rowodl->ODL_NUMERO }} as a last ditch attempt? – Peter Fox May 19 '16 at 10:42
  • @PeterFox This does not prevent Eloquent to cast PK to integer – Arcesilas May 19 '16 at 10:46
  • 2
    @Arcesilas possibly right, this might be what you need: http://stackoverflow.com/questions/34582535/laravel-5-2-use-a-string-as-a-custom-primary-key-for-eloquent-table-becomes-0 – Peter Fox May 19 '16 at 10:49
  • no, {{ (string)$rowitem->mykey }} does not work – lorenzo May 19 '16 at 13:00
  • thank you @PeterFox, but if you read my code you will see that I already defined $incrementing = false – lorenzo May 19 '16 at 13:03
  • @lorenzo my apologies then, there must be something else in your code that's doing the casting? Try adding an attribute accessor to your model and debug what value get's passed to the method? – Peter Fox May 19 '16 at 13:10
  • In my view I print out the $item value {{ dd($item) }} and "mykey" value is correct. It seems that the casting is made in the "echo" phase – lorenzo May 19 '16 at 13:20

0 Answers0