Code from template in controller

I have this in my template:

$id = Db::insert('main_category', [
  'name' => 'Utilities'
]);

$main = Db::select('main_category');
  foreach ($main as $name) {
    echo $name->name();
  }

and I’m trying to put that in my controller to test out how inserting and displaying from a database works before I code a form with submit button. I’ve gone through the controllers video and guide, but couldn’t figure it out. Can someone help me with putting that in a controller. I’m hoping that will then help me learn.

Only the $id and $main variable definitions would go into the controller.

The loop belongs in the template.

And the database insert would only happen if you have a post request from a form.

There are a lot of examples of forms and controllers in the cookbook: Forms | Kirby CMS

Thank you. I’ve seen the cookbook Forms. Right now, before dealing with the form and submission, I’m trying to learn the logic side of it.

And the database insert would only happen if you have a post request from a form.

Not really, I insert data on page reload. It’s only for me to understand the backend first. The code I posted worked and it inserted a new record, and then retrieved it.

As simple as it is to some, it’s difficult to me. Can someone help show me the code. I appreciate @moonwalk’s description, however, I would understand better seeing the code.

Not really sure what is unclear about the documentation: Controllers | Kirby CMS (text, not video)

The documentation is very clear. I’m just trying to understand how to apply it for my use case with Db::insert(), Db::select(), etc

Just like in the documentation/in your template, you define your variables $id and $main, and return them in the return array.

but the foreach statement belongs in the template, not the controller.

Maybe post what you tried and did not work.

Finally got it to work. Thank you @texnixe and @moonwalk. Both described the same thing and I just didn’t understand. Now I do. Thank you both.