Laravel database insertion while using a JWT - php

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

Related

Trying to create project for specific product id laravel-8

A user have many products and product have own id
2)And A product have many projects
I have trouble to make ProjectController
Note: if you need more details you can ask.
This is my user model user.php
public function Products(){
return $this->hasMany('App\Models\Product');
}
public function Project(){
return $this->hasMany('App\Models\Project');
}
This is my Product model product.php
public function User(){
return $this->belongsTo(User::class);
}
public function Project(){
return $this->hasMany('App\Models\Project');
}
This is my project model project.php
public function User(){
return $this->belongsTo(User::class);
}
public function Product(){
return $this->belongsTo(Product::class);
}
Here product table have user_id as forignId and project table have user_id and product_id as forign key
This is project table project.php
$table->unsignedBigInteger ('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreignId('product_id')->nullable();
This is here I have troubles in ProjectController.php
class ProjectController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
// $projects = Project::where('user_id',auth()->user()->id)->latest()->paginate(20);
$projects = Project::where('user_id',auth()->user()->id)->where('product_id')->latest()->paginate(20);
return view('projects.index', compact('projects'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('projects.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request,$id)
{
$request->validate([
'chapter_name' => 'required',
'sub_section_name' => 'required',
'title_1' => 'required',
'description_1' => 'required',
'image_1' => 'required',
'image_2' => 'required',
'image_3' => 'required',
'title_2' => 'required',
'description_2' => 'required',
'title_3' => 'required',
'description_3' => 'required',
'video_1' => 'required',
'video_2' => 'required',
'video_3' => 'required',
]);
// $input = $request->all();
$input['user_id'] = auth()->user()->id;
$input['product_id'] = $id;
Project::create($input);
return redirect()->route('project.index')
->with('success','Product created successfully.');
}
/**
* Display the specified resource.
*
* #param \App\Models\Project $project
* #return \Illuminate\Http\Response
*/
public function show(Project $project)
{
// $category = $project->category;
return view('projects.show', compact('project'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Project $project
* #return \Illuminate\Http\Response
*/
public function edit(Project $project)
{
return view('projects.edit', compact('project'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Project $project
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Project $project)
{
// $user_id = Auth::user()->id ;
$request->validate([
'chapter_name' => 'required',
'sub_section_name' => 'required',
'title_1' => 'required',
'description_1' => 'required',
'image_1' => 'required',
'image_2' => 'required',
'image_3' => 'required',
'title_2' => 'required',
'description_2' => 'required',
'title_3' => 'required',
'description_3' => 'required',
'video_1' => 'required',
'video_2' => 'required',
'video_3' => 'required',
]);
$input = $request->all();
$project->update($input);
return redirect()->route('project.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Project $project
* #return \Illuminate\Http\Response
*/
public function destroy(Project $project)
{
$project->delete();
return redirect()->route('projects.index')
->with('success', 'Project deleted successfully');
}
public function importProject()
{
Excel::import(new ProjectsImport, request()->file('file'));
return back()->with('success','Project created successfully.');
}
public function export()
{
return Excel::download(new UsersExport, 'projects.xlsx');
}
}
This is user table user.php
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->foreignId('current_team_id')->nullable();
$table->text('profile_photo_path')->nullable();
$table->timestamps();
});
This is products table products.php
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->text('detail');
$table->string('color');
$table->string('image');
$table->string('logo');
$table->unsignedBigInteger('user_id');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
This is project table project.php
Schema::create('projects', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('chapter_name', 255)->nullable();
$table->string('sub_section_name', 500)->nullable();
$table->string('title_1', 255)->nullable();
$table->string('description_1', 5000)->nullable();
$table->string('image_1', 255)->nullable();
$table->string('image_2', 255)->nullable();
$table->string('image_3', 255)->nullable();
$table->string('title_2', 255)->nullable();
$table->string('description_2', 5000)->nullable();
$table->string('title_3', 255)->nullable();
$table->string('description_3', 255)->nullable();
$table->string('video_1', 255)->nullable();
$table->string('video_2', 255)->nullable();
$table->string('video_3', 255)->nullable();
$table->unsignedBigInteger ('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
// $table->foreignId('product_id')->nullable();
$table->unsignedBigInteger('product_id')->references('id')->on('products')->onDelete('cascade');
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->nullable();
});
Thanks for help
Below are 2 possible causes of your error.
The uploaded file request()->file('file') lucks a column with header name id.
If this is the case you may wish to perform some sort of header validation during the import process. i.e:
<?php
namespace App\Imports;
use App\Models\Project;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class ProjectsImport implements ToCollection, WithHeadingRow
{
use Importable;
private const HEADING_NAMES = [
'chapter_name',
'sub_section_name',
'title_1',
'description_1',
'image_1',
'image_2',
'image_3',
'title_2',
'description_2',
'title_3',
'description_3',
'video_1',
'video_2',
'video_3',
'id'
];
private const HEADING_ROW = 0;
public function collection(Collection $rows)
{
if (
(count($columnHeadings = array_keys($rows[self::HEADING_ROW])) == count(self::HEADING_NAMES))
&& (array_diff($columnHeadings, self::HEADING_NAMES) === array_diff(self::HEADING_NAMES, $columnHeadings))
) {
redirect()
->back()
->withErrors([
"import" => "Incorrect excel sheet headers."
. " "
. "Expected:"
. " " . json_encode(self::HEADING_NAMES)
]);
}
// If validation fails, it won't reach the next statement.
foreach ($rows as $row) {
Project::create([
'chapter_name' => $row['chapter_name'],
// ...
]);
}
}
public function headingRow(): int
{
return self::HEADING_ROW;
}
}
You're using header names to access the data yet by default $row indexes are used instead. i.e: $row[0] instead of $row['chapter_name'].
If this is the case you may wish to implement the WithHeadingRow concern.
Laravel Excel | Heading Row
In case your file contains a heading row (a row in which each cells
indicates the purpose of that column) and you want to use those names
as array keys of each row, you can implement the WithHeadingRow
concern.
i.e:
<?php
use App\Models\Project;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class ProjectsImport implements ToModel, WithHeadingRow
{
public function model(array $row)
{
return new Project([
'chapter_name' => $row['chapter_name'],
// ...
]);
}
}
Addendum
If the uploaded file doesn't have the actual 'product_id's but instead has the product names, you could perform some sort of preprocessing to replace product names with their respective 'product_id's.
In addition, you could use some row validation to ensure that the product names exist in the database.
A. Validate product names making sure that they exist.
Laravel Excel | Row Validation without ToModel
<?php
namespace App\Imports;
use App\Models\Project;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class ProjectsImport implements ToCollection, WithHeadingRow
{
use Importable;
public function collection(Collection $rows)
{
Validator::make($rows->toArray(), [
// Table Name: 'products'. Table Column Name: 'name'. Excel Sheet Header Name: 'product_name'.
'*.product_name' => ['required', 'exists:products,name'],
])->validate();
// If validation fails, it won't reach the next statement.
foreach ($rows as $row) {
Project::create([
'chapter_name' => $row['chapter_name'],
// ...
]);
}
}
}
B. Perform some sort of preprocessing to replace product names with their respective 'product_id's
Laravel Excel | Mapping rows
By adding WithMapping you map the data that needs to be added as
row. This way you have control over the actual source for each column.
i.e:
<?php
namespace App\Imports;
use App\Models\Project;
use App\Models\Product;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMapping;
class ProjectsImport implements ToCollection, WithHeadingRow, WithMapping
{
use Importable;
public function collection(Collection $rows)
{
Validator::make($rows->toArray(), [
'*.chapter_name' => 'required',
'*.sub_section_name' => 'required',
'*.title_1' => 'required',
'*.description_1' => 'required',
'*.image_1' => 'required',
'*.image_2' => 'required',
'*.image_3' => 'required',
'*.title_2' => 'required',
'*.description_2' => 'required',
'*.title_3' => 'required',
'*.description_3' => 'required',
'*.video_1' => 'required',
'*.video_2' => 'required',
'*.video_3' => 'required',
'*.product_name' => ['required', 'exists:products,name'],
'*.product_id' => ['required', 'numeric', 'exists:products,id'],
])->validate();
foreach ($rows as $row) {
Project::create([
'chapter_name' => $row['chapter_name'],
'product_id' => $row['product_id']
// ...
]);
}
}
public function map($row): array
{
$mappedRow = $row;
$mappedRow['product_id'] = (isset($row['product_name'])
&& ($product = Product::firstWhere('name', $row['product_name'])))
? $product->id
: null;
return $mappedRow;
// From this point, your rules() and model() functions can access the 'product_id'
}
}
Addendum 2
It appears that your second where clause in index method is lucking (ProjectController).
// ...
public function index()
{
// $projects = Project::where('user_id',auth()->user()->id)->latest()->paginate(20);
$projects = Project::where('user_id',auth()->user()->id)->where('product_id')->latest()->paginate(20); ❌
return view('projects.index', compact('projects'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
// ...
A where clause requires at least 2 parameters. One 'product_id' parameter is passed for your case.

Getting ErrorException Trying to get property of non-object in laravel

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.

Problem with seeding users to database in Laravel

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(),
]);
}

Laravel Factory | The mapping is not specified

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;

ErrorException array to string conversion on migrate --seed

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

Categories