1

first time I ask via the web, but I don't know what I can do anymore. My question is about laravel using Eloquent. I have no problems with migrations and seeding and have a connection to MySQL. But when I try to build a controller and want to store data on my existing table car. here is an example:


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Car;

class DatenController extends Controller
{
    public function work()
    {
      $car = new Car;
      $car->save();
      return 'Erfolg!';
    }
}*

But when i want to start the URL which uses the method the following error arise:

Illuminate\Database\QueryException SQLSTATE[HY000] [2002] No such file or directory (SQL: insert into cars (updated_at, created_at) values (2022-01-16 13:26:17, 2022-01-16 13:26:17))

I looked into the other solutions but they only discuss the connection to MySQL and because of the migration, I think that my connection is totally fine. I tried everything with my env. and database.php file but found nothing wrong. maybe you can help me. Here my env. file:

APP_ENV=local
APP_KEY=base64:KpzUnnCIW9b+xWDdoMNy7F/Wwo1GlD8lN8lB4AnIG+I=
APP_DEBUG=true
APP_URL=http://pexam.test

LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=8889
DB_DATABASE=hallo
DB_USERNAME=root
DB_PASSWORD=root
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

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

MEMCACHED_HOST=memcached

REDIS_HOST=redis
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false

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}"

SCOUT_DRIVER=meilisearch
MEILISEARCH_HOST=http://meilisearch:7700


and here my database.php file:

use Illuminate\Support\Str;

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',
            'url' => env('DATABASE_URL'),
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
            'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
        ],

        'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '8889'),
            'database' => env('DB_DATABASE', 'hallo'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', 'root'),
            'unix_socket' => env('DB_SOCKET', '/Applications/MAMP/tmp/mysql/mysql.sock'),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

        'pgsql' => [
            'driver' => 'pgsql',
            'url' => env('DATABASE_URL'),
            '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',
            'url' => env('DATABASE_URL'),
            '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 body of commands than a typical key-value system
    | such as APC or Memcached. Laravel makes it easy to dig right in.
    |
    */

    'redis' => [

        'client' => env('REDIS_CLIENT', 'phpredis'),

        'options' => [
            'cluster' => env('REDIS_CLUSTER', 'redis'),
            'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
        ],

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

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

    ],

];

Additional here is the model car:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Car extends Model
{
  public $timestamps = true;
}

And here my car _migration:


use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCarsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cars', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('baujahr')->default(0);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('cars');
    }
}

Thank u for your help. I will answer quickly if anything is not clear enough.

Greetings Fermain

fermain
  • 51
  • 6
  • I tried [Stackoverflow question](https://stackoverflow.com/questions/54124262/how-to-fix-illuminate-database-queryexception-sqlstatehy000-1044-access-de) solution, this [from laracasts](https://laracasts.com/discuss/channels/laravel/illuminatedatabasequeryexception-1?page=1&replyId=599392) one even i have no server and run docker and others [like flutter](https://flutterq.com/solved-how-to-fix-illuminatedatabasequeryexception-sqlstatehy000-1044-access-denied-for-user/), [or stackoverflow](https://stackoverflow.com/questions/29695450/pdoexception-sqlstatehy000-2002-no-such-file-or-directory) – fermain Jan 16 '22 at 14:01
  • Could you share car model and car migration as well. By the way i dont understand what you are trying to save, you created empty object and trying to save it there. – Saroj Shrestha Jan 16 '22 at 14:05
  • It's mainly wrong with your code created_at and updated_at columns are not null so you have to cast those values into null in model level then it's working fine – Sai Tarun Jan 16 '22 at 14:09
  • try this one too https://stackoverflow.com/questions/29305502/php-artisan-migrate-with-mamp-and-unix-socket – N69S Jan 16 '22 at 14:16
  • larave uses PDO internally you can see here https://stackoverflow.com/questions/20723803/pdoexception-sqlstatehy000-2002-no-such-file-or-directory – Jerson Jan 16 '22 at 14:49
  • also you should get the mysql.sock path correctly. – Jerson Jan 16 '22 at 14:51
  • @Jerson Seed does work on my terminal only Eloquent don't and I got the mysql.sock path from the Mamp web start and there is information about username, password, and the .sock path – fermain Jan 16 '22 at 16:25
  • @N69S I tried ur link but it doesn't work – fermain Jan 16 '22 at 16:28
  • @SarojShrestha I shared the migration and the model in my question. Hope it helps to understand – fermain Jan 16 '22 at 16:31
  • @fermain seeding and migrating works fine? are you sure that table has been created in database? – Jerson Jan 16 '22 at 16:34
  • @Jerson yeah that is the Problem, everything works fine except eloquent. So the data tables were added and I did it from a tutorial 1 to 1 two times but it doesn't work to transfer the data from the controller. Seeding and Migration works fine every time i try – fermain Jan 16 '22 at 16:36
  • @fermain did you clear the config cache, php artisan config:clear – Jerson Jan 16 '22 at 16:39
  • I Tried it again, but it didn't work. Same alert – fermain Jan 16 '22 at 16:41
  • @fermain can you try using DB::select() or using query builder only like selecting the table in controller just for debugging purposes – Jerson Jan 16 '22 at 16:42
  • Under the QueryException from Routing, I see that the Controller *App\Http\Controllers\DatenController@work* is used but it says that the Route name is *unknown. Maybe there is something wrong? – fermain Jan 16 '22 at 16:45
  • @fermain can you make clone repo for that will try to reproduce – Jerson Jan 16 '22 at 16:48
  • @Jerson i did it like `public function work() { $cars = DB::table('cars')->get(); return view('cars.id', ['cars' => $cars]); }` But that don't work and give back same error Maybe any idea how to set
    to make the code more clear? I created the table with migration already but didnt stored any data inside already. so i expect not output but also no error
    – fermain Jan 16 '22 at 16:53
  • A clone repo means "gh repo clone Project"? Didn't do that ever before."gh repo clone FermainPariz/laravel-test" so this is my gh repo – fermain Jan 16 '22 at 17:00
  • German variable names are not exactly recommended ...then using English table names ?! – Martin Zeitler Jan 21 '22 at 09:41
  • I solved this issue, there were just two database and that was the problem – fermain Jan 21 '22 at 09:42
  • Does this answer your question? [PDOException SQLSTATE\[HY000\] \[2002\] No such file or directory](https://stackoverflow.com/questions/20723803/pdoexception-sqlstatehy000-2002-no-such-file-or-directory) – Martin Zeitler Jan 21 '22 at 09:43
  • No i tried but it didnt work – fermain Jan 21 '22 at 09:44
  • That was a rhetorical, auto-generated comment... while the socket basically is the only "file" being involved. Two databases are no problem at all ...but two MySQL instances trying to exclusively lock the same socket are. – Martin Zeitler Jan 21 '22 at 09:51

2 Answers2

1

I found the answer to my issue. I used MAMP and Docker at the same time. The problem is that Mama is on the server, and docker is lokal on the computer. So I got two databases. But the password for the database was not set in Docker. So I got access to my server database with the properties in env. And no access to my docker database, which the eloquent wanted to store. So I deleted MAMP from my computer and tried to access MySQL with

docker exec -it MySQL MySQL -uroot -p

but the password was wrong. So I used the command of What's the default password in docker container MySQL-server when you don't set one? from nischay, and this generates a new password. I set this password in docker exec -it MySQL MySQL -uroot -p, and I was in the MySQL bash. After this, I reset the password with ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password;

fermain
  • 51
  • 6
0

You have to provide created_at and updated_at values to time format otherwise you should update automatically when ever the data is created into that particular table.

You provide following line into the specific model

public $timestamps = true;
Sai Tarun
  • 569
  • 4
  • 14
  • i added this line to my code but there didn't changed anything. Added it to my Question in the code of the car model – fermain Jan 16 '22 at 16:14
  • and if i set $timestamp = false my QueryException throws `SQLSTATE[HY000] [2002] No such file or directory (SQL: insert into "cars" () values ())` – fermain Jan 16 '22 at 16:33
  • this is very wrong because $timestamps is true by default – Jerson Jan 16 '22 at 16:40