How to use substring with laravel eloquent?

by cortez.connelly , in category: PHP Frameworks , 6 months ago

How to use substring with laravel eloquent?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 6 months ago

@cortez.connelly 

In Laravel, you can use the SUBSTRING function in your Eloquent queries by using the selectRaw method. Here's an example:

1
$result = YourModel::selectRaw('SUBSTRING(column_name, start_position, length) as new_column')->get();


Replace YourModel with your actual model name and column_name, start_position and length with the appropriate values for your substring operation.


For example, if you have a User model and you want to select a substring of the name column starting from position 0 and with a length of 5 characters, you can do the following:

1
$users = User::selectRaw('SUBSTRING(name, 0, 5) as short_name')->get();


This will return a collection of users with a short_name attribute that contains the substring of the name column.