The Slim Framework support forum has moved to http://discourse.slimframework.com. This Tender forum is no longer maintained or monitored.

Raw query using Eloquent in Slim application

Bruno's Avatar

Bruno

12 Dec, 2014 02:58 PM

Hi,

I've spent several hours to find out how to use Raw query using Eloquent in Slim,
and I just want to share the solution.

Assuming you already registered your connection 'my_db' using $capsule->addConnection(). If you don't know how to do, you can easily find other discussions showing how to use "Eloquent outside of Laravel".

Then you do:

use Illuminate\Database\Capsule\Manager as Capsule;
$sql = 'SHOW COLUMNS FROM my_table';
$db = Capsule::connection( 'my_db' );
$result = $db->select( $db->raw($sql) );
print_r($result);

Of course, in such query, be sure to sanitize your data to avoid any SQL injection attack.

Regards,

Bruno

  1. 1 Posted by John Hunt on 16 Feb, 2016 10:31 AM

    John Hunt's Avatar

    Worked a treat - thanks! :)

  2. 2 Posted by Johan on 17 Feb, 2016 12:38 PM

    Johan's Avatar

    Why not create models extending Illuminate\Database\Eloquent\Model?

  3. 3 Posted by Bruno Martin on 17 Feb, 2016 01:04 PM

    Bruno Martin's Avatar

    I am interested to know it.

    Can you go further and show how you would do the following request?

    'SHOW COLUMNS FROM my_table'

  4. 4 Posted by Johan on 17 Feb, 2016 01:26 PM

    Johan's Avatar

    Hi Bruno,

    Sure:

    <?php
    
    use Illuminate\Database\Eloquent\Model;
    
    class User extends Model 
    {
    }
    
    $user = new User();
    $result = $user->attributesToArray();
    print_r($result);
    

    The advantage in extending the Eloquent Model class is that you have abstraction of your undelying database.
    Raw SQL will not work on all databases. Your example works on MySQL, but not on PostgreSQL.

  5. 5 Posted by Bruno Martin on 18 Feb, 2016 01:27 AM

    Bruno Martin's Avatar

    Of course!

    Thanks Johan!

  6. 6 Posted by Bruno Martin on 18 Feb, 2016 01:39 AM

    Bruno Martin's Avatar

    Hi Johan,

    Actually, I need more information from Columns that I don’t know how to get from Eloquent, like Type and Comment, any idea?
    The SQL request will return something like this:
    [Field] => fr
    [Type] => text
    [Collation] => utf8mb4_unicode_ci
    [Null] => NO
    [Key] =>
    [Default] =>
    [Extra] =>
    [Privileges] => select,insert,update
    [Comment] => Français (French)

Reply to this discussion

Internal reply

Formatting help / Preview (switch to plain text) No formatting (switch to Markdown)

Attaching KB article:

»

Attached Files

You can attach files up to 10MB

If you don't have an account yet, we need to confirm you're human and not a machine trying to post spam.

Keyboard shortcuts

Generic

? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac