I am trying to build a menu according to user roles using many to many relationship. laravel is my first php framework and i am facing this issue
Unhandled Exception
Message:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_role.created_at' in 'field list'
SQL: SELECT `roles`.*, `user_role`.`id` AS `pivot_id`, `user_role`.`created_at` AS `pivot_created_at`, `user_role`.`updated_at` AS `pivot_updated_at`, `user_role`.`user_id` AS `pivot_user_id`, `user_role`.`role_id` AS `pivot_role_id` FROM `roles` INNER JOIN `user_role` ON `roles`.`id` = `user_role`.`role_id` WHERE `user_role`.`user_id` = ?
Bindings: array (
0 => 1,
)
user migration:
<?php
class Users {
public function up()
{
Schema::create('users', function($table){
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('username', 128);
$table->string('password', 128);
$table->string('firstname', 128);
$table->string('lastname', 128);
$table->date('dob');
$table->string('phone')->nullable();
$table->text('image')->nullable();
$table->timestamps();
});
DB::table('users')->insert(array(
'username' => 'admin',
'password' => Hash::make('admin'),
'firstname' => 'asdf',
'lastname' => 'zxcv',
'dob' => '1990-02-23',
'phone' => '935735367'
));
}
function down()
{
Schema::drop('users');
}
}
roles migration:
<?php
class Role {
public function up()
{
Schema::create('roles', function($table){
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('lable', 60);
$table->string('url', 128)->default("#");
$table->integer('parent')->default("0");
$table->integer('level')->default("0");
$table->integer('sort')->default("0");
$table->integer('published')->default("0");
});
}
public function down()
{
Schema::drop('roles');
}
}
role_user
<?php
class Access {
public function up()
{
Schema::create('role_user', function($table){
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('role_id')->references('id')->on('roles');
});
}
public function down()
{
Schema::drop('role_user');
}
}
user model:
<?php
class User extends Basemodel{
public static $table = 'users';
public static $timestamps = true;
public static $rules = array(
'username' => 'required|min:3|alpha',
'password' => 'required|min:3|alpha'
);
public function roles()
{
return $this->has_many_and_belongs_to('Role');
}
public static function menu(){
$roles = User::find(1)->roles()->get();
return $roles;
}
}
Role Model
<?php
class Role extends Eloquent{
public static $table = 'roles';
}
Controller:
<?php
class Home_Controller extends Base_Controller {
public $restful= true;
public function get_index()
{
return View::make('home.index')
->with('title','App Index')
->with('menu',User::menu());
}
can someone guide me on what to do ?
It looks like, at first glance, the timestamp columns are missing in the user_role table.
If you add the two columns; created_at and updated_at to the table and set them to datetime it should fix it up for you!
Also by the looks of things, your roles table doesn't have these timestamps described above either. You should either add these or set a public static variable in the Role model to state that they aren't there. You can do this by writing public static $timestamps = false
Related
I have these:
posts table
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title', 64);
$table->string('teaser', 128)->nullable();
$table->text('content', 50000);
$table->timestamps();
});
}
posts model
use HasFactory;
protected $fillable = ['title', 'teaser', 'content'];
public function tags()
{
return $this->belongsToMany(Tag::class, 'post_tag', 'post_id', 'tag_id');
}
tag table
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('text', 32);
});
}
tag model
use HasFactory;
public $timestamps = false;
public $fillable = ['text'];
public function posts()
{
return $this->belongsToMany(Post::class, 'post_tag', 'tag_id', 'post_id');
}
post_tag table
public function up()
{
Schema::create('post_tag', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('post_id');
$table->unsignedInteger('tag_id');
});
}
When I try to create a new post with tags, I get this error:
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'test' for column `laravel`.`post_tag`.`tag_id` at row 1
INSERT INTO
`post_tag` (`post_id`, `tag_id`)
VALUES
(31, test)
This is how I'm trying to do it:
public function store(PostFormValidation $request)
{
$newpost = Post::create($request->validated());
$newpost->tags()->sync($request->tags);
return redirect(route('home'));
}
But why is it complaining about the timestamps, when I removed them from the migration and specified that I'm not using any in the model too? What am I missing?
The submitted "tags" is a multiple select.
I think your error is in:
$newpost->tags()->sync($request->tags);
I would recommend looking at this laravel doc to see that the format should be:
$newpost->tags()->sync([1, 2, 3]);
Or:
$newpost->tags()->sync([1 => ['expires' => true], 2, 3]);
You tyining instert in field tag_id 'test' word, but tag_id unsignedbiginteger
I'm trying to make an app where airbnb hosts can have a log of their bookings, I created three models: Home, Guest and Booking. Booking being the main player, I also think there should be a pivot table but I'm not sure which models should it link... I decided to go with booking_guest but I'm getting the following error when I create a booking:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'booking_id' cannot be null (SQL: insert into `booking_guest` (`booking_id`, `guest_id`) values (?, 1), (?, 2))
I do something like this in my BookingController:
public function create(Request $request)
{
$guestIds = Guest::latest()->take(2)->pluck('id');
$home = Home::findOrFail(1);
$booking = new Booking();
$booking->home_id = $home->id;
$booking->guests()->attach($guestIds);
$booking->save();
return response()->json([
'booking' => $booking,
]);
}
I'm not feeling too sure about this configuration, could you guys share some light on me.
These are my models:
class Home extends Model
{
public function guests()
{
return $this->belongsToMany('App\Models\Guest', 'guest_home', 'home_id', 'guest_id');
}
public function bookings()
{
return $this->hasMany('App\Models\Booking');
}
}
class Booking extends Model
{
public function guests()
{
return $this->belongsToMany('App\Models\Guest', 'booking_guest', 'booking_id', 'guest_id');
}
}
class Guest extends Model
{
public function bookings()
{
return $this->belongsToMany('App\Models\Booking', 'booking_guest', 'guest_id', 'booking_id');
}
}
My migrations:
//Booking guest pivot table
Schema::create('booking_guest', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('booking_id')->index();
$table->foreign('booking_id')->references('id')->on('bookings')->onDelete('cascade')->onUpdate('cascade');
$table->unsignedInteger('guest_id')->nullable()->index();
$table->foreign('guest_id')->references('id')->on('guests')->onDelete('cascade')->onUpdate('cascade');
$table->timestamps();
});
Schema::create('guests', function (Blueprint $table) {
$table->increments('id');
$table->string('fullName');
$table->text('country');
$table->timestamps();
});
Schema::create('bookings', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('home_id')->index();
$table->foreign('home_id')->references('id')->on('homes')->onDelete('cascade')->onUpdate('cascade');
$table->timestamp('entryDate')->nullable();
$table->timestamp('exitDate')->nullable();
$table->timestamps();
});
Schema::create('homes', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('host_id')->index();
$table->foreign('host_id')->references('id')->on('hosts')->onDelete('cascade')->onUpdate('cascade');
$table->string('fullAddress')->unique();
$table->integer('rooms')->unique();
$table->timestamps();
});
As you can see from here:
public function create(Request $request)
{
...
$booking = new Booking(); // <-- here
$booking->guests()->attach($guestIds); // <-- here
$booking->save(); // <-- here
...
}
you are creating a new instance of Booking, then associating to it a Guest and then saving the instance of Booking.
However ->attach(...) tries to associate the Booking with the Guest, but the Booking does not exists at that time on the DB.
I would suggest to use Booking::create, so that after that statement, the booking exists on the DB and so you can attach to it the Guest:
public function create(Request $request)
{
$guestIds = Guest::latest()->take(2)->pluck('id');
$home = Home::findOrFail(1);
$booking = Booking::create([ // <- using Booking::create
'home_id' => $home->id // <- using Booking::create
]); // <- using Booking::create
$booking->guests()->attach($guestIds);
return response()->json([
'booking' => $booking,
]);
}
I have a table has many relation to other tables but it seperated with entity value please look at this :
i have this schema
public function up()
{
Schema::create('cards', function(Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('user_id')->unsigned()->nullable();
$table->integer('entity_id');
$table->string('entity');
$table->integer('qty')->nullable()->default('1');
});
}
public function up()
{
Schema::create('tickets', function(Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('title');
$table->string('summary');
$table->integer('amount');
$table->integer('stock')->default('0');
$table->integer('discount')->default('0');
});
}
public function up()
{
Schema::create('products', function(Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('title');
$table->integer('amount');
$table->integer('discount');
$table->text('description');
$table->integer('stock')->default('0');
});
}
and this relation in models
class Card extends Model
{
protected $table = 'cards';
public $timestamps = true;
public function ticket()
{
return $this->belongsTo('App\Models\Ticket', 'entity_id');
}
public function product()
{
return $this->belongsTo('App\Models\Product', 'entity_id');
}
}
i need to set where entity = 'ticket' before use belongsTo i mean is a table hase relation to many table base entity_id and i seperated it by entity column and base same vlue most have realation just.
You can do simply in your eloquent model file. do like this :
public function ticketWithCondition()
{
return $this->belongsTo('App\Models\Ticket', 'entity_id')->where('entity' , 'ticket');
}
public function ticket()
{
return $this->belongsTo('App\Models\Ticket', 'entity_id');
}
call like this :
// for show Card with EntityCondition
$comments = Card::find(123)->with('ticketWithCondition');
// for show comments without EntityCondition
$comments = Card::find(123)->with('ticket');
in my database i have product_category and products that one product maybe belongs to one or some category in product_category table, now my question is: when user on submitting product with one or some category how can i save that on database to have for example one category have one or some product?
in view i have multiple select as:
{{ Form::select('categories[]', $productCategories, null, array('class' => 'multiselect-success multiselect_selected','multiple'=>'multiple')) }}
products model:
class Products extends Model
{
protected $table = 'products';
protected $guarded = ['id'];
protected $casts = [
'images' => 'array'
];
public function productCategories()
{
return $this->belongsTo(ProductCategories::class);
}
}
productCategories model:
class ProductCategories extends Model
{
protected $table = 'product_categories';
protected $guarded =['id'];
protected $casts=[
'images'=>'array'
];
public function products()
{
return $this->hasMany(Products::class);
}
}
and store function into controller:
public function store(RequestProducts $request)
{
try {
$data = Products::create([
'name' => $request->name,
'amount' => $request->amount,
'product_code' => $request->product_code,
'weight' => $request->weight
/* MY PROBLEM IS HERE */
'category_id' => $request->categories
]);
} catch (Exception $ex) {
...
}
return redirect(route('manageProductCategories.index'));
}
in html view categories is an array and how can i implementing that?
UPDATE
after update code with createMany i get this error:
General error: 1364 Field 'category_id' doesn't have a default value (SQL: insert into `products` (`name`, `lang`, `amount`, `product_code`, `weight`, `images`, `updated_at`, `created_at`) values (eqweqwe, fa, 45,000, asd, asdasd, '', 2017-12-09 04:45:44, 2017-12-09 04:45:44))
migration files:
public function up()
{
Schema::create('product_categories', function (Blueprint $table) {
$table->increments('id');
$table->string('category_name');
$table->string('lang', 2);
$table->text('images');
$table->timestamps();
});
}
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('amount');
$table->string('product_code');
$table->string('weight');
$table->string('lang', 2);
$table->text('images');
$table->integer('category_id')->unsigned()->index();
$table->foreign('category_id')->references('id')->on('product_categories')->onDelete('cascade');
$table->timestamps();
});
}
From your question and comments, I understand the following.
Many products may have the category "category_1" and "product_1" may belongs to many categories.
To implement this you have to use "Many To Many" relationship.
I have updated your code, this might help you.
Migrations:
public function up()
{
Schema::create('product_categories', function (Blueprint $table) {
$table->increments('id');
$table->string('category_name');
$table->string('lang', 2);
$table->text('images');
$table->timestamps();
});
}
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('amount');
$table->string('product_code');
$table->string('weight');
$table->string('lang', 2);
$table->text('images');
$table->timestamps();
});
}
public function up()
{
Schema::create('products_product_category', function (Blueprint $table) {
$table->integer('product_id');
$table->integer('product_category_id');
});
}
Models
products model:
class Products extends Model
{
protected $table = 'products';
protected $guarded = ['id'];
protected $casts = [
'images' => 'array'
];
public function productCategories()
{
return $this->belongsToMany(ProductCategories::class,'products_product_category');
}
}
productCategories model:
class ProductCategories extends Model
{
protected $table = 'product_categories';
protected $guarded =['id'];
protected $casts=[
'images'=>'array'
];
public function products()
{
return $this->belongsToMany(Products::class, 'products_product_category');
}
}
Controller
public function store(RequestProducts $request)
{
try {
$data = Products::create([
'name' => $request->name,
'amount' => $request->amount,
'product_code' => $request->product_code,
'weight' => $request->weight
]);
$data->productCategories()->sync($request->categories);
} catch (Exception $ex) {
...
}
return redirect(route('manageProductCategories.index'));
}
Hope it will helps..
Model 1:
namespace App;
use Illuminate\Database\Eloquent\Model;
class productDescription extends Model
{
protected $table="ProductDescription";
protected $connection="mysql";
public function productPricing()
{
return $this->belongsTo(priceInfo::class);
}
public function salesPackage()
{
return $this->hasMany(packageModel::class);
}
}
Model2:
class packageModel extends Model
{
//
protected $table="subSalesPackage";
protected $connection="mysql";
public function product_description(){
return $this->belongsTo(productDescription::class);
}
}
Controller:
public function addProductDetails(Request $formdescription,$dataId)
{
$description=new productDescription;
$description->deviceCategoryId=$dataId;
$description->productdescriptionid=$this->getproductDescriptionId();
$description->modelName=$formdescription->input('mname');
$description->batteryType=$formdescription->input('batteryType');
//$description->salesPackage =$formdescription->input('package');
$description->skillSet =$formdescription->input('skillSet');
$description->Colour=$formdescription->input('colour');
$description->Material =$formdescription->input('material');
$description->maxAge=$formdescription->input('maxage');
$description->minAge =$formdescription->input('minage');
//$product->productPricing()-save($priceInfo);
//$product->productDetails()->save($description);
$description->save();
$salesPackage=new packageModel;
$salesPackage->salesPackage=$formdescription->input('package');
**$salesPackage->product_description()->associate($description);**
$salesPackage->save();
//echo("success");
return response()->json([
'modelName' => $formdescription->mname,
'colour' => $formdescription->colour,
'rechargable' => $formdescription->rechargable,
'batteryType' => $formdescription->batteryType
]);
//$description->product()->associate($priceInfo);
}
Migration->productdescription:
public function up()
{
//
Schema::create('ProductDescription', function (Blueprint $table) {
$table->engine='InnoDB';
$table->string('productdescriptionid')->primary();
$table->string('product_id');
$table->string('salesPackage');
$table->timestamps();
$table->index(['productDescriptionId']);
});
}
This is my migration for 1st table(model).It has the primary key as'productdescriptionid'.
Migration->subSalespackage
public function up()
{
//
Schema::create('subSalesPackage', function (Blueprint $table) {
$table->increments('id');
$table->string('product_description_id');
$table->string('salesPackage');
$table->foreign('product_description_id')-
>references('productdescriptionid')->on('ProductDescription');
$table->timestamps();
$table->index(['id']);
});
}
Here I have referred the productdescriptionid as foreign key.And when I add this salespackage table,the values should get added with the value of productdescriptionid(productDescription).
But the error i'm getting is can't able to add or update a child row.
You should try this:
return response()->json([
'SKUID' => $priceInfo->SKUID,
'listingStatus' => $priceInfo->listingStatus,
'MRP' => $priceInfo->MRP,
'sellingPrice' => $priceInfo->sellingPrice,
'id' =>$this->getproductId()
]);