Welcome Guest, Not a member yet? Register   Sign In
Run a seeder using a php script, without spark CLI
#1

Hello, I hope somebody can help me. I'm very new to CodeIgniter and to this forum. I am currently following a tutorial by Alain Rivest - https://includebeer.com/en/blog/how-to-b...r-4-part-4 - and spent the whole day trying to run a seeder. 
Is there any way to do this without using spark from CLI? Is there a way to call a php script from the browser URL? If so, could you please show me an example of a script for doing this?
Or if anybody could provide simple instructions on how to successfully use CLI with CI on a VPS, I would really appreciate it! 
I've spent so many hours trying to use terminal through cPanel (I am on a VPS) but the PHP version is wrong on there (5.6) and the installed version on the server is 7.4. I think this is why it keeps bringing up an error: 
"Parse error: syntax error, unexpected ':', expecting '{' in /home/apex5/apex_sys/system/Common.php on line 45". 
Here is line 45 from system/Common.php (which I have not modified in any way at all)
if (! function_exists('app_timezone')) {
    /**
    * Returns the timezone the application has been set to display
    * dates in. This might be different than the timezone set
    * at the server level, as you often want to stores dates in UTC
    * and convert them on the fly for the user.
    */
    function app_timezone(): string ===> This is line 45
    {
        $config = config(App::class);

        return $config->appTimezone;
    }
}

------------------------------------------
and in App.php line 111 is this, (not modified from original)
    public $appTimezone = 'America/Chicago';
-----------------------------------------
I have tried using sudo after adding the user into the wheel group users in WHM, to try and change the php version showing in terminal but it doesn't allow permission (spent hours trying to troubleshoot this and it's made me really stressed and shaking legs!).
All I need to do is run the seeder so that I can load the database table with the sample data records and finish the tutorial. I can then get back to building my main application!
Many, many thanks in advance!
Reply
#2

(This post was last modified: 04-28-2022, 01:29 PM by datamweb.)

Hello, welcome to codeigniter
To run seeder exit the terminal, you can use the following method
The code items are simple.

app\Database\Seeds\KishanSeeder.php
Code:
<?php

namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;

class KishanSeeder extends Seeder
{
    public function run()
    {

        $data = [
        'field _name1'                  => 'Kishan field 1',
        'field _name2'                 => 'Kishan field  2',
        ];

        $this->db->table('table_name')->insert($data);
    }
}

app\Controllers\Home.php

Code:
<?php

namespace App\Controllers;


class Home extends BaseController
{
    public function index()
    {
        return command('db:seed KishanSeeder');
     
    }
}

Now see http://SiteName.com/home via the browser. KishanSeeder will run.

In general, all php spark commands can be used anywhere via the following code:

Code:
command('command_name');

Enjoy Codigniter!
Reply
#3

Hi datamweb,
Many thanks for your instructions, I really appreciate it! I have followed what you wrote but unfortunately I get: 
404 - File Not Found.... Can't find a route for 'home'. 
I also tried Home, home.php, Home.php
I think it's because I followed that tutorial which has custom routes written in Routes.php
Is there a route I could write specifically to allow that Home.php file to be called in the URL?

Here is what's in Routes.php




Code:
$routes->addPlaceholder('slug', '[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*');

// Define routes for /, recipe/id and recipe/slug
$routes->get('/', 'RecipesController::index');
$routes->get('recipe/(:num)', 'RecipesController::recipeById/$1');
$routes->get('recipe/(:slug)', 'RecipesController::recipeBySlug/$1');
I have tried to modify this with no success.  And also placed "return command('dbConfusedeed KishanSeeder');" in the RecipesController.php file (from the tutorial) but it did not add anything to the database when that file got accessed.
Thanks again!
Reply
#4

Please temporarily rename app\Config\Routes.php to app\Config\InactiveRoutes.php.

Then create a new file called app\Config\Routes.php

with the following content:

Code:
<?php

namespace Config;

// Create a new instance of our RouteCollection class.
$routes = Services::routes();

// Load the system's routing file first, so that the app and ENVIRONMENT
// can override as needed.
if (file_exists(SYSTEMPATH . 'Config/Routes.php')) {
    require SYSTEMPATH . 'Config/Routes.php';
}

/*
* --------------------------------------------------------------------
* Router Setup
* --------------------------------------------------------------------
*/
$routes->setDefaultNamespace('App\Controllers');
$routes->setDefaultController('Home');
$routes->setDefaultMethod('index');
$routes->setTranslateURIDashes(false);
$routes->set404Override();
$routes->setAutoRoute(true);

/*
* --------------------------------------------------------------------
* Route Definitions
* --------------------------------------------------------------------
*/

// We get a performance increase by specifying the default
// route since we don't have to scan directories.
$routes->get('/', 'Home::index');

/*
* --------------------------------------------------------------------
* Additional Routing
* --------------------------------------------------------------------
*
* There will often be times that you need additional routing and you
* need it to be able to override any defaults in this file. Environment
* based routes is one such time. require() additional route files here
* to make that happen.
*
* You will have access to the $routes object within that file without
* needing to reload it.
*/
if (file_exists(APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php')) {
    require APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php';
}

now . Do the above description.
If you did not succeed with this method. Angry
Please submit the contents of seeder file and the migration file for review. Shy
Reply
#5

Hi datamweb, thanks for your support on this! I followed your instructions and it is now showing this error:
ErrorException #64

CodeIgniter\Autoloader\Autoloader::main(): Failed opening required '/var/www/html/index.php' (include_path='.:/opt/cpanel/ea-php74/root/usr/share/pear')
SYSTEMPATH/Commands/Server/rewrite.php at line 43
Code:
36 // then let the request handle it like normal.
37 if ($uri !== '/' && (is_file($path) || is_dir($path))) {
38     return false;
39 }
40
41 // Otherwise, we'll load the index file and let
42 // the framework handle the request from here.
43 require_once $fcpath . 'index.php';
44 // @codeCoverageIgnoreEnd
45

The KishanSeeder.php file is exactly how you wrote it, Routes.php is updated with your code also and there is no migration file.
I tried calling home, Home home.php, Home.php from the URL.
Thanks! Smile
Reply
#6

(04-29-2022, 05:44 AM)Kishan Anand Wrote: Hi datamweb, thanks for your support on this! I followed your instructions and it is now showing this error:
ErrorException #64

CodeIgniter\Autoloader\Autoloader::main(): Failed opening required '/var/www/html/index.php' (include_path='.:/opt/cpanel/ea-php74/root/usr/share/pear')
SYSTEMPATH/Commands/Server/rewrite.php at line 43
Code:
36 // then let the request handle it like normal.
37 if ($uri !== '/' && (is_file($path) || is_dir($path))) {
38     return false;
39 }
40
41 // Otherwise, we'll load the index file and let
42 // the framework handle the request from here.
43 require_once $fcpath . 'index.php';
44 // @codeCoverageIgnoreEnd
45

The KishanSeeder.php file is exactly how you wrote it, Routes.php is updated with your code also and there is no migration file.
I tried calling home, Home home.php, Home.php from the URL.
Thanks! Smile
Please read this first.
Did you configure the database?
Did you create a table in the database?
Please send me a backup file of the tables through php my admin , then select the database, then option Exporting .
Optionally via private message.
Also provide the contents of the latest file in this path:

root\writable\logs

I practically tested the method I presented, there is no problem in implementation.
We need more details to investigate.
Reply
#7

You need to read the CodeIgniter 4 User Guide, the autoRoute has been updated.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#8

(This post was last modified: 04-30-2022, 02:42 PM by kenjis.)

`command()` runs CLI command.
If you want to run seeder via web, you don't need to use `command()`,
Call the seeder directly in your controller.
Reply
#9

(This post was last modified: 04-30-2022, 05:22 PM by datamweb.)

(04-29-2022, 05:44 AM)Kishan Anand Wrote: Hi datamweb, thanks for your support on this! I followed your instructions and it is now showing this error:
ErrorException #64

CodeIgniter\Autoloader\Autoloader::main(): Failed opening required '/var/www/html/index.php' (include_path='.:/opt/cpanel/ea-php74/root/usr/share/pear')
SYSTEMPATH/Commands/Server/rewrite.php at line 43
Code:
36 // then let the request handle it like normal.
37 if ($uri !== '/' && (is_file($path) || is_dir($path))) {
38     return false;
39 }
40
41 // Otherwise, we'll load the index file and let
42 // the framework handle the request from here.
43 require_once $fcpath . 'index.php';
44 // @codeCoverageIgnoreEnd
45

The KishanSeeder.php file is exactly how you wrote it, Routes.php is updated with your code also and there is no migration file.
I tried calling home, Home home.php, Home.php from the URL.
Thanks! Smile

This problem is due to incorrect adjustment DOCUMENT_ROOT.
To go to CPanel , select Domains.
Then click the Manage button in front of the your domain name.
then change the Document Root: to yoursitename.ir/public
Then button Update.
See yoursitename.ir Or yoursitename.ir/home Or yoursitename.ir/home/index now.
Everything is working fine.The data enters the table without any problems.

Or:The second method: use the method described in @kenjis .
Just use command
Code:
$seeder = \Config\Database::seeder();
$seeder->call('KishanSeeder');
instead of command('dbConfusedeed KishanSeeder').

Thanks so much for the @kenjis tips here. The right solution(#5943) is provided by him.
Reply
#10

Thank you very much for the help, @datamweb and @kenjis it is now all working!
Reply




Theme © iAndrew 2016 - Forum software by © MyBB