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;
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;
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.
for the moment, i'am creating my product link to my category directly from my code in my seed doing
->categories()->attach(1) at the end of each product.
From my database, I can create a product but i can't link them with a foreign key to a category that is already in category_product_table.
I have 3 table : products, categories and category_product.
2020_04_09_073846_create_products_table
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned()->index();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->string('name');
$table->string('slug');
$table->string('category');
$table->string('description');
$table->string('releaseDate');
$table->float('price');
$table->timestamps();
});
}
ProductSeeder
<?php
use Illuminate\Database\Seeder;
use App\Product;
class ProductSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Product::create([
'name' => 'Halo 5',
'slug' => 'halo-5',
'category_id' => '1',
'category' => 'Xbox One',
'description' => "Halo 5: Guardians sur Xbox One est un FPS mettant en scène les aventures du Master Chief et d'un nouveau personnage, le Spartan Jameson Locke. ",
'releaseDate' => '27 octobre 2015',
'price' => '54.99'
]);
2020_05_02_201337_create_categories_table
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('slug')->unique();
$table->timestamps();
});
}
CategorieSeeder
<?php
use Carbon\Carbon;
use App\Category;
use Illuminate\Database\Seeder;
class CategorieSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$now = Carbon::now()->toDateTimeString();
DB::table('categories')->insert(
array(
array(
'name' => 'Xbox',
'slug' => 'xbox',
),
array(
'name' => 'Playstation',
'slug' => 'playstation',
),
array(
'name' => 'PC',
'slug' => 'pc',
),
array(
'name' => 'Switch',
'slug' => 'switch',
),
)
);
}
}
2020_05_03_105839_create_category_product_table
public function up()
{
Schema::create('category_product', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->unsigned()->nullable();
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->integer('category_id')->unsigned()->nullable();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
}
Product.php
class Product extends Model
{
public function categories()
{
return $this->AsOne('App\Category');
}
}
Category.php
class Category extends Model
{
public function products()
{
return $this->belongsToMany('App\Product');
}
}
HomeController
public function public(){
if (request()->category) {
$home = Product::with('categories')->whereHas('categories', function ($query){
$query->where('slug', request()->category);
})->get();
$categories = Category::all();
$categoryName = $categories->where('slug', request()->category)->first()->name;
} else {
$home = Product::inRandomOrder()->paginate(9);
$categories = Category::all();
$categoryName = 'Featured';
}
return view('home.index')->with([
'home' => $home,
'categories' => $categories,
'categoryName' => $categoryName,
'mode' => 'public'
]);
If someone can help me, thanks for your help !
php artisan make:migration create_products_table --create=products
php artisan migrate:refresh
use directly this command and add
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 studying some Laravel and at some point I had to re-migrate the database because I had to change a table. I'm using postman to do testing, and one of the api methods give me the error:
SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: events.user_id (SQL: insert into "events" ("sport", "title", "players", "when", "description", "location", "updated_at", "created_at") values (Hockey, Grass Hockey, 12, 30/09/2018, Come join us, Fairview park, 2018-11-08 22:19:45, 2018-11-08 22:19:45))
so it seems to be a problem with the events.user_id which I changed on a table called Events to have a relationship with the Users table. Some examples I found by researching is on table fields that were not ids, so I don't how to figure this one out, maybe some of you can help me!
here are the migrations for Events and Users:
public function up()
{
Schema::create('events', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
$table->string('sport');
$table->string('title');
$table->decimal('players', 8, 2);
$table->date('when');
$table->mediumText('description');
$table->string('location');
$table->timestamps();
});
}
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Here are the models:
class Event extends Model
{
protected $fillable = [
'sport',
'title',
'players',
'when',
'description',
'location'
];
public function user()
{
return $this->belongsTo('App\User');
}
class User extends Authenticatable
{
use HasApiTokens, 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',
];
public function events()
{
return $this->hasMany('App\Event');
}
}
And below is the api method that is giving me the error:
Route::post('/admin/create-event', function (Request $request) {
$data = $request->all();
$event = Event::create(
[
'sport' => $data['sport'],
'title' => $data['title'],
'players' => $data['players'],
'when' => $data['when'],
'description' => $data['description'],
'location' => $data['location'],
]
);
return $event;
});
Thanks guys!
Edit:
Route::middleware('auth:api')->post('/admin/create-event', function (Request $request) {
$user = $request->user();
$data = $request->all();
$event = Event::create(
[
'user_id' => \Auth::user()->id,
'sport' => $data['sport'],
'title' => $data['title'],
'players' => $data['players'],
'when' => $data['when'],
'description' => $data['description'],
'location' => $data['location'],
]
);
return $event;
});
I think you have to add 'user_id' to $fillable of Event class:
class Event extends Model
{
protected $fillable = [
'sport',
'title',
'players',
'when',
'description',
'location',
'user_id'
];
public function user()
{
return $this->belongsTo('App\User');
}
}
You need to pass the user_id:
'user_id' => \Auth::user()->id
The example above requires an authenticated user in the session, but if you are making the request using postman you probably don’t have one.
Anyway, you need to provide the user_id that will be stored in the database.
EDIT
Eloquent's method create will copy to the model only the attributes defined as fillable. So you have two options:
Add user_id to $fillable
Use newInstance instead of create, manually set the user_id with $event->user_id = ..., and manually save the $event model with $event->save();