简体   繁体   中英

Illuminate \ Database \ QueryException (2002) SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from `rents`)

I'm trying to connect a Laravel project to an existing database.

I have followed the Eloquent Model Conventions ; however, I am still hitting the following error:

Illuminate \\ Database \\ QueryException (2002) SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from rents )

Here is my code:

web.php

Route::get('/', [
    'uses' => 'RentsController@index'
    ]);

RentsController.php

<?php

namespace App\Http\Controllers;

use App\Rent;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;


class RentsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {   
        $rents = Rent::all();
        return view('welcome', ['rents' => $rents]);
    }

    ...
}

Rent.php

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;


class Rent extends Model {
    protected $table = 'rents';
}

welcome.blade.php

<!doctype html>
<html>
    <head>
    </head>
    <body>
        <ul>
            @foreach ($rents as $rent)
                <li>{{ $rent->title }}</li>
            @endforeach
        </ul>
    </body>
</html>

* One thing that may be the problem is that I am running the page locally (php artisan serve), while the database is real and online. Would that cause the issue? If so, any idea how to fix that? *

Any idea what could be the problem? I have the .env file setup correctly, as it works on another page. However, on this one, it does not seem to be able to find the 'rents' table.

Thanks!!

Everyone, thank you for your help!

I figured it out. The problem was the DB_HOST.

I am running the page locally (ie php artisan serve) and the database is online. I do not have access to the database on my local computer. This is why it couldn't connect.

So, instead of DB_HOST = localhost OR 127.0.0.1, I put it to the actual host.

For example:

DB_HOST=hostname_from_server
DB_PORT=3306
DB_DATABASE=database_name_on_server
DB_USERNAME=username_on_server
DB_PASSWORD=password_on_server

Then, I needed to clear the cache in the terminal:

php artisan config:cache
php artisan cache:clear

Props to @ AddWeb Solution Pvt Ltd for the help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM