This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

JeroenvanRensen
JeroenvanRensen

Hi everyone,

I'm creating a component in OctoberCMS, and I want to show all the product types in the database. I'm unable to make a database connection, and I've no idea how to do it.

Here's my code:

public function onRun() {
    $types = Db::select('select * from types');
    echo $types;
}

Does ayone know how to do this?

Thank you! Jeroen van Rensen

JeffGoldblum
JeffGoldblum

That's not how the query builder works. I suggest you read up on https://octobercms.com/docs/database/model, https://octobercms.com/docs/database/query, https://laravel.com/docs/5.5/queries, & https://laravel.com/docs/5.5/eloquent and related articles.

If the type is represented by a Model class then you can do

public function onRun() {
    return Type::all()->toJson();
}

Otherwise you'd do

public function onRun() {
    return Db::table('types')->get()->toJson();
}
JeroenvanRensen
JeroenvanRensen

Hello, thank you very much! He works now!

hansnijssen64233
hansnijssen64233

Hi Jeroen, Your example could almost work: in your php file, you just need to add 'use Db' in the using statements, on top of the page, like this:

 <?php namespace YourNamespace\YourPlugin\Components;  
use Cms\Classes\ComponentBase;  
use ApplicationException;  
use Db;  

and then loop through the object, something like this:  
$products = Db::table('yourtable')->get();    
        foreach ($products as $product) {  
        echo "<h4>" . $product->prod_nr . "</h4>";  
        echo "<h4>" . $product->prod_name . "</h4>";  
        echo "<br>";  
       }

Last updated

1-4 of 4

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.