0

When I make a new table in Laravel, I generally use the Laravel default id column definition: $table->bigIncrements('id'); Say for example I have a clients table with that in my migration.

If I need a foreign relationship on another table, I 'll do it like this:

$table->unsignedBigInteger('client_id');                

$table->foreign('client_id')
      ->references('id')->on('clients')
      ->onDelete('cascade');

However, if I get model instances of both of those tables and render them with ->toJson();, the id of the first table will be an integer in JSON, while the client_id of the second table will be a string in the json output.

Now I can make a $casts=[] array in the Model class for the second table to cast it to an integer, but I don't know if there's any reason I shouldn't do that. Or maybe I should ALWAYS do that. Is there any guidelines or suggestions about this sort of thing?

TKoL
  • 13,158
  • 3
  • 39
  • 73
  • There is no need. It's just for mapping database types to PHP types (or objects), but unsignedBigInteger already maps to int. – online Thomas Oct 25 '19 at 12:09
  • I sometimes have a need in my javascript though, when one record has its ids as integers and the foreign relationship table has its foreign ids as strings. – TKoL Oct 25 '19 at 12:18
  • Then your migration or your table definition is not what you think it is. The value is always returned as an integer in every case I've seen. – miken32 Oct 25 '19 at 14:07
  • @miken32 I've definitely looked at everything and this is the second server this has happened on (I'm relatively new to PHP/Laravel, so that's as much data as I have). My migration definitely says `unsignedBigInteger`, and the column type, when I look in the SQL, is `bigint(20)`. I feel like it's 1 of 2 situations: (1) I should be expecting an integer in this case, and not worry about it, or (2) these servers I'm working on have a strange PHP setting that is converting number values to Strings when it comes from SQL (something which happens in normal PHP anyway iirc) – TKoL Oct 28 '19 at 12:11
  • @miken32 something like this perhaps: https://stackoverflow.com/questions/20079320/php-pdo-mysql-how-do-i-return-integer-and-numeric-columns-from-mysql-as-int/20123337#20123337 – TKoL Oct 28 '19 at 12:13
  • From `artisan tinker` do `var_dump(User::first()->client_id);` substituting with whatever model you are using. If it says it's a string, and `SHOW CREATE TABLE users` in MySQL shows an integer type, then go file a bug report with Laravel. – miken32 Oct 28 '19 at 14:59

0 Answers0