I'm trying to set up my very first laravel project however when I try to have artisan to seed the database with faker it throws
[errorException] array to string conversion
I'm just working with the stock users migration file
and using the command php artisan migrate --seed
Any guidance would be greatly appreciated
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->string('role', array('user', 'admin', 'superuser'));
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
and this UserTableSeeder that artisan generated for me
use Illuminate\Database\Seeder;
class UserTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
factory(App\User::class, 49)->create();
factory(App\User::class)->create([
'name' => 'admin',
'role' => 'admin',
]);
}
}
this is my Modelfactory.php
$factory->define(App\User::class, function ($faker) {
return [
'name' => $faker->name,
'email' => $faker->email,
'password' => str_random(10),
'remember_token' => str_random(10),
'role' => $faker->word->randomElement(array('user','superuser')),
];
});
$table->string('role', array('user', 'admin', 'superuser'));
You are selecting a type of string and then providing an array.
This is exactly what your error is talking about.
Your error is because of this line
$table->string('role', array('user', 'admin', 'superuser'));
change string to enum; ex:
$table->enum('role', array('user', 'admin', 'superuser'));
this will execute.
You say string but provide an array in this line:
$table->string('role', array('user', 'admin', 'superuser'));
You should use :
$table->enum('role', ['user', 'admin', 'superuser']);
For reference see here:
https://laravel.com/docs/5.8/migrations#creating-columns
Related
I am using fortify for creating and logging-in users. So as I add a new column 'role' in my database as well as in the model. I face this kind of error when signing-up a new user. Somehow, the user information will still be registered and stored in the database but an error is shown as I click Register. How do I fix this ? Below are my code.
Fortify, CreateNewUser.php
<?php
namespace App\Actions\Fortify;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Laravel\Fortify\Contracts\CreatesNewUsers;
use Laravel\Jetstream\Jetstream;
class CreateNewUser implements CreatesNewUsers
{
use PasswordValidationRules;
/**
* Validate and create a newly registered user.
*
* #param array $input
* #return \App\Models\User
*/
public function create(array $input)
{
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => $this->passwordRules(),
'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['accepted', 'required'] : '',
])->validate();
$user = User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => Hash::make($input['password']),
'role' => 'user',
]);
}
}
user controller
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index()
{
$user = User::get();
return view('users.index', compact('user'));
}
}
users table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('staff_id')->nullable();
$table->string('name');
$table->string('email')->unique();
$table->string('department')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('role');
$table->rememberToken();
$table->foreignId('current_team_id')->nullable();
$table->string('profile_photo_path', 2048)->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
};
You are missing the return inside your function.
$user = User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => Hash::make($input['password']),
'role' => 'user',
]);
return $user;
I'm trying to create an order requiring a bearer token. Here what I'm trying to do is, decoding the token's payload to get the user's ID who requested to create an order, and insert that ID to orders table's userId column .I'm having a hard time with this error which is "userId doesn't have a default value". These are my migrations
Orders Table
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->string('orderCode');
$table->bigInteger('userId')->unsigned();
$table->foreign('userId')->references('id')->on('users');
$table->bigInteger('productId')->unsigned();;
$table->foreign('productId')->references('id')->on('products');
$table->integer('quantity');
$table->string('address');
$table->date('shippingDate');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('orders');
}
};
Products Table
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id('id');
$table->string('name');
$table->integer('amount');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('products');
}
};
Users Table
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
};
And this is the method in the controller that I'm trying to use:
public function createOrder(Request $request)
{
$token = $request->bearerToken();
$credits = json_decode(base64_decode(str_replace('_', '/', str_replace('-', '+', explode('.', $token)[1]))));
$user = (int)($credits->sub);
$request->validate([
'orderCode' => 'required|string|max:8',
'productId' => 'required|integer',
'quantity' => 'required|integer',
'address' => 'required|string',
'shippingDate' => 'required|date'
]);
$productId = $request->productId;
$quantity = $request->quantity;
$myProduct = Product::find($productId);
if (!$myProduct) {
return response()->json([
'status' => 'error',
'message' => 'Product not found!'
], 404);
} else {
if ($myProduct->amount < $request->quantity) {
return response()->json([
'status' => 'error',
'message' => 'Invalid quantity (more than amount or negative)!'
], 400);
} else {
$order = Order::create([
'orderCode' => $request->orderCode,
'userId' => $user,
'productId' => $productId,
'quantity' => $quantity,
'address' => $request->address,
'shippingDate' => $request->shippingDate
]);
return response()->json([
'status' => 'success',
'message' => 'order created successfully',
'order' => $order
]);
}
}
}
The error I'm having Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1364 Field 'userId' doesn't have a default value (SQL: insert into orders (orderCode, productId, quantity, address, shippingDate, updated_at, created_at) values (ABC12345, 2, 500, Wall Street, 2022-12-12, 2022-09-01 09:56:43, 2022-09-01 09:56:43)) in file C:\Users\kamilcoban\Desktop\rest-api-task\vendor\laravel\framework\src\Illuminate\Database\Connection.php on line 759
but I assign a value to $user, using the token. In users table IDs are bigint and unsigned. Is this declaration occuring the problem? Or I missing somewhere?
When I dd($user) it prints ^1 which is the userId
I'm trying to store my form data in my laravel application on the store method.
public function store(Request $request)
{
$this->validate($request, [
'subDomainName' => 'required',
'subDomainSuffix' => 'required',
'lang' => 'required',
'themeid' => 'required',
'paymentoption' => 'required',
'packageType' =>'required',
'domain' => 'unique:apps',
]);
$user = Auth::user();
$fullDomain = $request->domain;
$dbName = $this->dumpNewDB($fullDomain);
$appId = $this->getNextId();
// create record in app table
Website::create([
'domain' => $fullDomain,
'masterUserId' => $request->user,
'dbName' => $dbName,
'host' => env('DB_HOST', '127.0.0.1'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', 'root'),
'theme' => $request->themeid,
'lang' => $request->lang,
'status' => 1,
'package_type' => $request->packageType,
'payment_option' => $request->paymentoption,
'isAppCreated' => 1,
'isDefault' => 0,
]);
}
and also i have a function to dump a db as well
public function dumpNewDB($domain)
{
Tenant::new()->withDomains($domain)->save();
$tenant = DB::table('domains')->where('domain', $domain)->first();
\Artisan::call('tenants:migrate', [
'--tenants' => [$tenant->tenant_id]
]);
\Artisan::call('tenants:seed', [
'--tenants' => [$tenant->tenant_id]
]);
return $tenant->tenant_id;
}
When ever I run the following functions I'm getting following error,
ErrorException
Trying to get property 'tenant_id' of non-object
Database migration for my apps table as follows,
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAppsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('apps', function (Blueprint $table) {
$table->bigIncrements('appId');
$table->string('domain')->unique();
$table->bigInteger('masterUserId')->unsigned();
$table->string('dbName');
$table->string('host');
$table->string('username');
$table->string('password');
$table->string('theme');
$table->string('lang');
$table->date('renewDate')->nullable();
$table->date('renewedDate')->nullable();
$table->tinyInteger('status');
$table->bigInteger('package_type')->unsigned();
$table->string('payment_option');
$table->tinyInteger('isAppCreated');
$table->string('stripeCustomerId')->nullable();
$table->tinyInteger('subscrStatus')->nullable();
$table->dateTime('reSubTime')->nullable();
$table->dateTime('upgradeTime')->nullable();
$table->tinyInteger('isDefault')->nullable();
$table->foreign('masterUserId')
->references('id')
->on('users');
$table->foreign('package_type')
->references('id')
->on('packages');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('apps');
}
}
My database migrations for the tenant,
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTenantsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up(): void
{
Schema::create('tenants', function (Blueprint $table) {
$table->string('id', 36)->primary(); // 36 characters is the default uuid length
// (optional) your custom, indexed columns may go here
$table->json('data');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down(): void
{
Schema::dropIfExists('tenants');
}
}
And domains,
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateDomainsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up(): void
{
Schema::create('domains', function (Blueprint $table) {
$table->string('domain', 255)->primary();
$table->string('tenant_id', 36);
$table->foreign('tenant_id')->references('id')->on('tenants')->onUpdate('cascade')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down(): void
{
Schema::dropIfExists('domains');
}
}
I have included all the required imports for multi tenant. But When ever I try to run my store method and create new record I'm getting
ErrorException
Trying to get property 'tenant_id' of non-object
error and tenant db or record in app table not get created.
I am trying to seed users in database but I get error saying
Symfony\Component\Debug\Exception\FatalThrowableError : Call to a member function random() on bool
I have users table and genders table with gender_id in users table that points to Man or Woman column in genders table with hasMany relationship. I want to be able to write gender_id automatically in users table when I seed the database and create a new user. Currently with this code I get that error from above and NULL in gender_id column, but rest it inserts correctly in both users and genders table. When I remove random() function then it inserts always 1 in gender_id, but I want to be able to write 1 or 2 randomly. Also when I dump $genders it returns TRUE. Is there some way around this, any help is appreciated. Here is my code.
UserSeeder.php
<?php
use Carbon\Carbon;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$genders = DB::table('genders')->insert([
[
'genders' => 'Woman',
],
[
'genders' => 'Woman Looking For Woman',
],
[
'genders' => 'Man',
]
]);
//dd($genders);
DB::table('users')->insert([
'gender_id' => $genders->random(),
'name' => 'authuser',
'email' => 'authuser#auth.com',
'email_verified_at' => now(),
'password' => Hash::make('auth123456'),
'age' => 18,
'remember_token' => Str::random(10),
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
}
}
users table
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('gender_id')->nullable();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->default();
$table->integer('age')->default()->nullable();
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
genders table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateGendersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('genders', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('genders');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('genders');
}
}
User.php
public function gender()
{
return $this->belongsTo(Gender::class, 'gender_id', 'id');
}
Gender.php
public function users()
{
return $this->hasMany(User::class, 'gender_id', 'id');
}
You can pluck your id values from Gendre and do randomly on that like this:
$genders = DB::table('genders')->insert([
['genders' => 'Woman'],
['genders' => 'Woman Looking For Woman'],
['genders' => 'Man']
]);
$gendreIds = Genders::pluck('id');
DB::table('users')->insert([
'gender_id' => $gendreIds->random(),
...
]);
This will give you gender which exists in database.
Sometimes seed wouldn't give you id's from 1 to 3.
So I think it's not best solution to use rand(1,3).
Good luck!
In your user creation method
Instead of
'gender_id' => $genders->random(),
you can use this
'gender_id' => rand(1,3),
No need to add genders here.You can do that in other seeder or manually do that.Here in your genders id should be in 1,2 & 3 .fixed.THen you can use rand() function here.rand() is a php function .rand() define a random number & you can fixed it value like rand(min,max) so just here use this rand(1,3)
public function run()
{
$genders = DB::table('genders')->insert([
[
'genders' => 'Woman',
],
[
'genders' => 'Woman Looking For Woman',
],
[
'genders' => 'Man',
]
]);//your wish to seed this gender in here
DB::table('users')->insert([
'gender_id' => rand(1,3),
'name' => 'authuser',
'email' => 'authuser#auth.com',
'email_verified_at' => now(),
'password' => Hash::make('auth123456'),
'age' => 18,
'remember_token' => Str::random(10),
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
}
I'm trying to create some mock data using faker for a Model called Product to test Scout & ElasticSearch but unfortunately, I'm getting an error. When I use factory(App\Product::class, 200)->create() inside of php artisan tinker to generate the data, I get the following error: LogicException with message 'Nothing to update: the mapping is not specified.' Any pointers on which other files I should look at
App > Product.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use ScoutElastic\Searchable;
class Product extends Model {
use Searchable;
protected $indexConfigurator = ProductIndexConfigurator::class;
protected $fillable = ['sku', 'name', 'type', 'price', 'upc', 'category', 'shipping'
, 'description', 'manufacturer', 'model', 'url', 'image'];
public function products ()
{
return $this->belongsTo('App\Product');
}
}
ProductFactory.php
<?php
$factory->define(App\Product::class, function (Faker\Generator $faker) {
return [
'sku' => $faker->randomDigit,
'name' => $faker->name,
'type' => $faker->name,
'price' => $faker->randomDigit,
'upc' => $faker->randomDigit,
'category' => $faker->name,
'shipping' => $faker->randomDigit,
'description' => $faker->name,
'manufacturer' => $faker->name,
'model' => $faker->name,
'url' => $faker->url,
'image' => $faker->url,
];
});
Migration - create_products_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('product', function(Blueprint $table) {
$table->increments('id');
$table->string('sku');
$table->string('name');
$table->string('type');
$table->string('price');
$table->string('upc');
$table->string('category');
$table->string('shipping');
$table->string('description');
$table->string('manufacturer');
$table->string('model');
$table->string('url');
$table->string('image');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('product');
}
}
Your code is OK and works for me, you're just missing the properties $table and $timestamps on your Product model:
class Product extends Model
{
public $table = 'product';
public $timestamps = false;