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.
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 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 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
I'm working with Laravel 4 and trying to seed the database with some users. I'm using the Zizaco Confide plugin, so my User model extends ConfideUser instead of Eloquent per the documentation. I added a few fields to the model also, but nothing super complicated. I have tried removing those fields but I get the same issue.
I created a UserSeeder class that I call with the DatabaseSeeder and then run php artisan migrate:refresh --seed. It runs without error and returns "The database has been seeded", and that is true for every table except users. No users ever get inserted. I've tried creating the user with User::create(array(...)) as well as $user = new User ... $user->save() and I get the same results. No errors are dumped, and nothing is in any log I can find on the system. If I insert some var_dumps in the UserSeeder->run() method, I see that the objects are created with the correct values, but nothing saves.
What am I missing? Here's some code samples, I can provide more if needed:
models\User.php:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
use Zizaco\Confide\ConfideUser;
//class User extends Eloquent implements UserInterface, RemindableInterface {
class User extends ConfideUser
{
// for Entrust
use \Zizaco\Entrust\HasRole;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
public function agency()
{
if ($this->agency_type == 'local')
{
return $this->hasOne('Local');
}
if ($this->agency_type == 'county')
{
return $this->hasOne('County');
}
}
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
database\migrations\xxxxxxxxx_confide_setup_users_table.php:
<?php
use Illuminate\Database\Migrations\Migration;
class ConfideSetupUsersTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
// Creates the users table
Schema::create('users', function($table)
{
$table->increments('id');
$table->string('username');
$table->string('email');
$table->string('password');
$table->string('confirmation_code');
$table->boolean('confirmed')->default(false);
$table->string('address1');
$table->string('address2')->nullable();
$table->string('state', 2);
$table->string('zipcode', 9);
$table->string('phone', 10);
$table->string('extension',5 )->nullable();
$table->string('fax', 10)->nullable();
$table->enum('agency_type', array('local', 'county', 'state'))->default('local');
$table->integer('agency')->unsigned()->nullable();
$table->dateTime('last_seen');
$table->timestamps();
$table->softDeletes();
});
// Creates password reminders table
Schema::create('password_reminders', function($t)
{
$t->string('email');
$t->string('token');
$t->timestamp('created_at');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('password_reminders');
Schema::drop('users');
}
}
database\seeds\UserSeeder.php:
<?php
use \Illuminate\Database\Seeder;
class UserSeeder extends Seeder
{
public function run()
{
DB::table('users')->delete();
User::create(
array(
'username' => 'local_test',
'email' => 'nathan#abc.com',
'password' => Hash::make('local'),
'confirmation_code' => '483JU3ID8',
'confirmed' => true,
'address1' => '123 Main St.',
'state' => 'MI',
'zipcode' => '12345',
'phone' => '5559993436',
'agency_type' => 'local',
'agency' => null,
'last_seen' => new DateTime
)
);
Do this in your user seeder class:
class UsersTableSeeder extends Seeder
{
public function run()
{
DB::table('users')->truncate();
$users = array(
array( 'username' => 'local_test',
'email' => 'nathan#abc.com',
'password' => Hash::make('local'),
'confirmation_code' => '483JU3ID8',
'confirmed' => true,
'address1' => '123 Main St.',
'state' => 'MI',
'zipcode' => '12345',
'phone' => '5559993436',
'agency_type' => 'local',
'agency' => null,
'last_seen' => new DateTime
)
);
// make sure you do the insert
DB::table('users')->insert($users);
}
}
and then, make sure you invoke it in your DatabaseSeeder.php file
<?php
class DatabaseSeeder extends Seeder {
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$this->call('UsersTableSeeder');
}
}
Confide uses Ardent for validation. adding 'password_confirmation' property is required. Also you don't need to Hash::make since Confide will also handle that for you.
<?php
class UsersTableSeeder extends Seeder
{
public function run()
{
DB::table('users')->truncate();
$users = array(
array( 'username' => 'local_test',
'email' => 'nathan#abc.com',
'password' => 'local',
'password_confirmation' => 'local',
'confirmation_code' => '483JU3ID8',
'confirmed' => true,
'address1' => '123 Main St.',
'state' => 'MI',
'zipcode' => '12345',
'phone' => '5559993436',
'agency_type' => 'local',
'agency' => null,
'last_seen' => new DateTime
)
);
// make sure you do the insert
DB::table('users')->insert($users);
}
}
I found that the seeder fails silently.
I was seeing a user table. The return was a seed success but it was empty.
I followed the answer above using the insert method.
When doing the above method, an error was returned saying that a column did not have a default value in the database table.
I adjusted the column and reverted back to the create method from the laravel doc.
It was then successful.
So in my instance the there was a database error but it failed without telling me.
With the insert method I was able to find the error.
Then the create method worked once there were no errors.