Laravel framework

Печать RSS
1089

P

Чатланин
0
Знает ли кто-нибудь почему выдает такую ошибку?
D:\OSPanel\domains\host>php artisan migrate:fresh --seed
Dropped all tables successfully.
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table (0.02 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table (0.02 seconds)
Migrating: 2020_01_12_184642_create_posts_table
Migrated:  2020_01_12_184642_create_posts_table (0.02 seconds)

   Symfony\Component\Debug\Exception\FatalThrowableError  : Class 'App\User' not found

  at D:\OSPanel\domains\host\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:228
    224|         if ($this->amount < 1) {
    225|             return (new $this->class)->newCollection();
    226|         }
    227| 
  > 228|         $instances = (new $this->class)->newCollection(array_map(function () use ($attributes) {
    229|             return $this->makeInstance($attributes);
    230|         }, range(1, $this->amount)));
    231| 
    232|         $this->callAfterMaking($instances);

  Exception trace:

  1   Illuminate\Database\Eloquent\FactoryBuilder::make([])
      D:\OSPanel\domains\host\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:178

  2   Illuminate\Database\Eloquent\FactoryBuilder::create()
      D:\OSPanel\domains\host\database\seeds\DatabaseSeeder.php:14

Беда в том, что класс User на месте
Изменил: php (15.01.2020 / 03:48)

Господин ПЖ
0
Миграцию покажи и класс User
P

Чатланин
0
Вантуз-мен, User.php
<?php

namespace host;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Добавлено через 00:43 сек.
<?php

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

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('post_id');
            $table->bigInteger('author_id')->unsigned();
            $table->string('title');
            $table->string('descr');
            $table->text('text');
            $table->timestamps();
            $table->foreign('author_id')->references('id')->on('users');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}
Изменил: php (15.01.2020 / 17:45)

Господин ПЖ
0
namespace host; -> Class 'App\User' not found
Изменил: Вантуз-мен (15.01.2020 / 17:48)
P

Чатланин
0
Вантуз-мен, я что-то не догоню никак) код миграции в пространство имен user добавить нужно?

Добавлено через 00:35 сек.
Только какой смысл дважды одно и то же писать

Господин ПЖ
0
По тому коду который ты скинул не видно вызов класса User, судя по всему он не в миграции а в сидах которые выполняются после миграций с ключом --seed
По ошибке понятно что вызывается класс User который в пространстве имен App
у тебя User в host
из этого следует, что App\User !== host\User

замени namespace host; на namespace App; у тебя скорее всего по ошибке вставилось
P

Чатланин
0
D:\OSPanel\domains\host>php artisan migrate:fresh --seed
Dropped all tables successfully.
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table (0.02 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table (0.01 seconds)
Migrating: 2020_01_12_184642_create_posts_table
Migrated:  2020_01_12_184642_create_posts_table (0.03 seconds)

   Symfony\Component\Debug\Exception\FatalThrowableError  : Class 'App\User' not found

  at D:\OSPanel\domains\host\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:228
    224|         if ($this->amount < 1) {
    225|             return (new $this->class)->newCollection();
    226|         }
    227| 
  > 228|         $instances = (new $this->class)->newCollection(array_map(function () use ($attributes) {
    229|             return $this->makeInstance($attributes);
    230|         }, range(1, $this->amount)));
    231| 
    232|         $this->callAfterMaking($instances);

  Exception trace:

  1   Illuminate\Database\Eloquent\FactoryBuilder::make([])
      D:\OSPanel\domains\host\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:178

  2   Illuminate\Database\Eloquent\FactoryBuilder::create()
      D:\OSPanel\domains\host\database\seeds\DatabaseSeeder.php:14

  Please use the argument -v to see more details.


Мне кажется до этого правильное пространство имен было

Добавлено через 02:41 сек.
Легче вручную заполнить

Добавлено через 06:04 сек.
ладно, пошвыряюсь. Все равно полезно узнать как там "под капотом" все устроено
Изменил: php (15.01.2020 / 18:10)

Голубые штаны
0
php, Вантус прав. Приведи у себя весь код к единому пространству имен.
P

Чатланин
0
Дмитрий, возможно. Незнаю как, но проблему решил переустановкой двига. Потом свой код обратно скопироаал и все заработало.
Изменил: php (16.01.2020 / 08:31)
P

Чатланин
0
Дошло дело до "мускула" и я полез смотреть официальную документацию (официальную, Карл!) и воспользовался предложенным там методом table(), в моем случае это выглядит так:
$posts = post::table('posts') -> get();
        return view('index', compact('posts'));
В итоге:
Bad Method Call
Did you mean App\post::getTable() ?

Решил попробовать и getTable(), но и тут ошибка: "короче, не статический метод".
Не знаете ли, почему двиг снова уперся рогом и выдал ошибку выше?
Изменил: php (21.01.2020 / 13:18)
Стикеры / Теги / Правила / Топ тем / Топ постов / Поиск