adam Kearsley adam Kearsley - 2 months ago 17
MySQL Question

Laravel Fluent Queries - How do i perform a 'SELECT AS' using Fluent?

I am quite new to Laravel and Fluent queries.
I have a query to select all the rows from the hire table and display them in a random order.

DB::table('hire_bikes')->order_by(\DB::raw('RAND()'))->get();


I now want to be able to do is put

concat(SUBSTRING_INDEX(description, " ",25),"...") AS description


into the SELECT part of the query, so that i can select * from the table and a shortened description.

I know this is possible by running a raw query, but i was hoping to be able to do this using Fluent or at least partial Fluent (like above).

Any help or ideas?

Thanks
Adam.

Answer

You can do this by by adding a DB::raw() to a select array in your fluent query. I tested this locally and it works fine.

DB::table('hire_bikes')
  ->select(
      array(
        'title',
        'url',
        'image',
        DB::raw('concat(SUBSTRING_INDEX(description, " ",25),"...") AS description'),
        'category'
      )
    )
  ->order_by(\DB::raw('RAND()'))
  ->get();
Comments