How to Cast String into int in Laravel model

How to Cast String into int in Laravel model

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Why Casting Strings to Integers in Laravel Models Needs Care

You might find yourself in a situation where your database column is defined as a string, but you absolutely need it treated as an integer within your application logic. The immediate instinct is often to wrap the retrieval with a cast operator. As shown in the common pattern $code = (int)$ratings;, this syntax works perfectly fine in pure PHP and will handle the conversion at runtime without error.

However, relying solely on this approach inside your model's accessor methods creates a specific type of fragility known as the "Eager Loading Problem." When you access a relationship that includes the attribute you are trying to cast, Laravel does not call your accessor method for that relationship instance. Instead, it pulls the raw column value directly from the database and returns it.

If you rely on the (int) cast inside an accessor like getRatingsAttribute(), the conversion simply never happens when that specific relationship is loaded eagerly. The result is inconsistent data types throughout your application: some instances of the model have a string, while others have an integer, depending entirely on how they were retrieved. This inconsistency makes writing unit tests difficult and can lead to subtle bugs where arithmetic operations fail or cause unexpected type coercion warnings in strict environments.

To resolve this without relying on eager-loading quirks, you should define the attribute as a Casted column in your model definition. Laravel provides a dedicated trait for exactly this scenario: Illuminate\Database\Eloquent\Casts\AsInteger. By applying this cast to the $casts array property within your Model class, you ensure that every time the model is hydrated from the database—whether it's the main query or an eager-loaded relationship—the framework automatically converts the value to an integer before returning it to your controller.

Here is how you implement this:

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\AsInteger;

class Rating extends Model
{
    protected $casts = [
        'ratings' => AsInteger::class,
    ];
}

Using AsInteger is generally preferred over the shorthand (int) cast for several reasons. First, it explicitly communicates to other developers reading your code that this field is intended to be an integer. Second, it handles null values gracefully without throwing type errors, whereas a direct (int) (null) cast results in a warning rather than a clean 0. Third, it future-proofs your application against changes in how relationships are loaded.

There is also the option of using the string 'integer' or 'int' as a key in the $casts array. While this achieves the same result and is slightly more concise, the dedicated class AsInteger::class offers better type hinting support if you ever need to refactor your model properties to use strict typing declarations.

One potential pitfall involves database schema design. If you are storing numeric ratings, consider whether a string column is truly necessary in the first place. Storing an integer directly in the database avoids any casting overhead entirely and allows for efficient indexing and sorting. However, if there is a legacy requirement to keep the data as text—perhaps to preserve leading zeros or specific formatting—using the cast ensures your application logic remains robust regardless of the underlying storage type.

Remember that these casts apply globally to every instance of the model. If you are dealing with a scenario where you need the raw string value for a specific edge case, you can access the attribute before casting by using the $attributes array directly within the model or accessing the underlying property via magic methods, though this usually indicates a deeper architectural issue that should be addressed rather than worked around.

For further reading on database migrations and type safety in Laravel ecosystems, resources like https://laravelcompany.com can provide additional context on maintaining clean data types across your stack.

Our network