How to interact with database from public folder file in Laravel?

Viewed 730

I have a file test.php in public/test folder. Now I want to retrieve data from the database. I have tried with below way and it doesn't work. It is showing an error. How can I interact with the database from this test.php file?

Fatal error: Uncaught Error: Class 'App\Test' not found

use App\Test;

define('DB_TYPE', 'mysql');
define('DB_USER', 'root');
define('DB_HOST', 'localhost');
define('DB_PORT', '3306');
define('DB_PASSWORD', '');
define('DB_NAME', 'testing');

$test = new Test();
$test->addConnection([
    'driver' => DB_TYPE,
    'host' => DB_HOST,
    'port' => DB_PORT,
    'database' => DB_NAME,
    'username' => DB_USER,
    'password' => DB_PASSWORD,
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix' => '',
    'strict' => false,
    'engine' => null,
]);
$test->setAsGlobal();
$test->bootEloquent();
$configs = $test->index();

Test.php model:

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Capsule\Manager as DB;

class Test extends Model
{
    public static function index() {
        $configs = DB::select('select * from tests');
    }
}
2 Answers

The public directory should only be for things you want to serve publicly. Such as css files, js files and template images.

You must make your model inside your App folder. Make your own folder inside your App folder (in your case which is public, i think) so that's how you will access it

use App\public\test

I hope this answer will help you.

Definitely it will not work because the class is not found in the file you executed. Either you need to explicitly include the class or include the composer autoload file in order to import those classes. Just try adding the following to your test.php

require_once '../vendor/autoload.php';
Related