behnampmdg3's avatar

Da phUck? Weird issue with database access. Ignoring .env?

Tinker works fine smooth like a Swedish bikini model.

But in browser I get

lluminate \ Database \ QueryException (1045)
SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES) (SQL: select * from `posts`)

routes

<?php

Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::resource('posts', 'PostController');
Route::resource('users', 'UserController');

.env

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:qy+LgqHkDP4JJxFQ307iqMLoeiDU7wPTk6nlGH0hQpE=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=auth_project
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

<?php

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $posts = Post::all();
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function show(Post $post)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function edit(Post $post)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Post $post)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function destroy(Post $post)
    {
        //
    }
}

database

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Database Connection Name
    |--------------------------------------------------------------------------
    |
    | Here you may specify which of the database connections below you wish
    | to use as your default connection for all database work. Of course
    | you may use many connections at once using the Database library.
    |
    */

    'default' => env('DB_CONNECTION', 'mysql'),

    /*
    |--------------------------------------------------------------------------
    | Database Connections
    |--------------------------------------------------------------------------
    |
    | Here are each of the database connections setup for your application.
    | Of course, examples of configuring each database platform that is
    | supported by Laravel is shown below to make development simple.
    |
    |
    | All database work in Laravel is done through the PHP PDO facilities
    | so make sure you have the driver for your particular database of
    | choice installed on your machine before you begin development.
    |
    */

    'connections' => [

        'sqlite' => [
            'driver' => 'sqlite',
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
        ],

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
        ],

        'pgsql' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
            'schema' => 'public',
            'sslmode' => 'prefer',
        ],

        'sqlsrv' => [
            'driver' => 'sqlsrv',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '1433'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | Migration Repository Table
    |--------------------------------------------------------------------------
    |
    | This table keeps track of all the migrations that have already run for
    | your application. Using this information, we can determine which of
    | the migrations on disk haven't actually been run in the database.
    |
    */

    'migrations' => 'migrations',

    /*
    |--------------------------------------------------------------------------
    | Redis Databases
    |--------------------------------------------------------------------------
    |
    | Redis is an open source, fast, and advanced key-value store that also
    | provides a richer set of commands than a typical key-value systems
    | such as APC or Memcached. Laravel makes it easy to dig right in.
    |
    */

    'redis' => [

        'client' => 'predis',

        'default' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_DB', 0),
        ],

        'cache' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_CACHE_DB', 1),
        ],

    ],

];

0 likes
14 replies
bobbybouwmann's avatar

You might have your config cached locally! So to uncache your config you can run this on the command line php artisan config:clear

If that doesn't work you need to tell us a bit more about your local environment! It could be that you need to restart nginx for example because that is caching a lot of things (probably not, but it happens!).

Also you sad you have database access in tinker? But not on your local environment? Never heard of that before though :P

Snapey's avatar

Sounds like your browser is connecting to the wrong install of Laravel.

Check that your web server is pointing to the right directory

behnampmdg3's avatar

Yes I am connected to the right one.

This works:

PostController

 public function index()
    {
        echo "hi"; //Prints hi in ther browser
    }
php artisan config:clear

Didn't do it either.

(And yes Tinker works fine).

Very strange.

Where is Cronix when you need one?

drjd's avatar

Looks like it could definitely be environment related. The error you posted says it's attempting to connect to MySQL using the username homestead but your .env file sets DB_USERNAME to root. The fallback username would be forge as defined in config/database.php so it definitely feels like there's another environment variable being read from somewhere.

I'd be tempted to add a quick and dirty route closure to routes/web.php to check this through the browser rather than Tinker if that's seeming to be fine.

Route::get('/test', function () {
    return env('DB_USERNAME', 'Cannot find value');
});

If hitting this route returns homestead it's somehow not hitting the right .env file, if it returns root you know it's hitting the right .env file and the plot thickens... and if it returns Cannot find value it can't find the environment variable at all which is unlikely.

lostdreamer_nl's avatar

It's also possible to set environment variables in Apache / Nginx....

You migth want to make sure you're not setting them in some .htaccess file or something (and thus overriding the .env version when running via the webserver).

behnampmdg3's avatar
Route::get('/test', function () {
    return env('DB_USERNAME', 'Cannot find value');
});

homestead

behnampmdg3's avatar

Never had this issue before. This is Laravel out of the box new project.

drjd's avatar

The default .env.example file sets DB_USERNAME to homestead. Though it might sound silly, are you absolutely certain the contents of the .env file you posted above are from this project directory?

behnampmdg3's avatar

Yes. Because in .env I change the DB_DATABASE to aaaaaa. Start Tinker again and

>>> App\User::all()
Illuminate/Database/QueryException with message 'SQLSTATE[HY000] [1049] Unknown database 'aaaaaa' (SQL: select * from `users`)'

I change it back to auth_project, exit and start Tinker again and I get this:

>>> App\User::all()
=> Illuminate\Database\Eloquent\Collection {#2937
     all: [
       App\User {#2938
         id: 1,
         name: "Viola Deckow",
         email: "[email protected]",
         email_verified_at: "2018-10-22 03:41:42",
         created_at: "2018-10-22 03:41:42",
         updated_at: "2018-10-22 03:41:42",
       },
       App\User {#2939
         id: 2,
         name: "Esta Schmitt",
         email: "[email protected]",
         email_verified_at: "2018-10-22 03:41:42",
         created_at: "2018-10-22 03:41:42",
         updated_at: "2018-10-22 03:41:42",
       },

These are settings for .env

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:qy+LgqHkDP4JJxFQ307iqMLoeiDU7wPTk6nlGH0hQpE=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=auth_project
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

These are the settings for .env.example

APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=auth_project
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

.htaccess

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

behnampmdg3's avatar
behnampmdg3
OP
Best Answer
Level 5

OK! found it!

In the terminal: Ctr + C, then "php artisan serve" again. Works now!

Damn, that was weird.

Thanks, everyone for helping.

bobbybouwmann's avatar

@behnampmdg3 That's exactly what I told you!

If that doesn't work you need to tell us a bit more about your local environment! It could be that you need to restart nginx for example because that is caching a lot of things (probably not, but it happens!).

When you run php artisan serve your local config is cached until you stop the application and restart it. That's how a server works, it can run a process but it's hard to change that process while it's running!

Please or to participate in this conversation.