How to use substring with laravel eloquent?

by cortez.connelly , in category: PHP Frameworks , a year ago

How to use substring with laravel eloquent?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , a year 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.

Related Threads:

How to join 3 tables using laravel eloquent?
How to get a all eloquent models in laravel?
How to prevent duplicates in laravel eloquent?
How to chain eloquent relation in route in laravel?
How to convert sql query to eloquent in laravel?
How to join sub-query in laravel eloquent?