Why am I unable to NOT use timestamps in Laravel? - php

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

Related

Laravel relationship return null

I have a store that is using a payment package
Now I want to show the items that were purchased, but I run into this problem
Controller
public function mycourse()
{
$courses = PurchasedCourse::where('user_id', Auth::id())
->with('course')
->get();
dd($courses);
return view('student.courses.mycourse', [
'courses' => $courses
]);
}
Model
public function course()
{
return $this->belongsTo(Course::class, 'id');
}
Migration
public function up()
{
Schema::create('courses', function (Blueprint $table) {
$table->id('id');
$table->string('name')->unique();
$table->string('start');
$table->string('end');
$table->integer('price');
$table->string('jalasat');
$table->string('zarfiat');
$table->text('tozih');
$table->integer('hit');
$table->string('department');
$table->string('thumbnail');
$table->tinyInteger('status')->default(0);
$table->string('slug')->unique();
$table->timestamps();
});
}
Your relationship method is wrong. The syntax for the belongsTo() method is
belongsTo(class, ?foreign_id, ?related_id). In your case, it should be:
public function course()
{
return $this->belongsTo(Course::class, 'course_id', 'id');
}
or just
public function course()
{
return $this->belongsTo(Course::class);
}
since your columns follow Laravel's naming conventions.

JSON response with all columns for a many-to-many relation in Laravel

I am using two models in Laravel which are linked via a many-to-many relation. The models are Pictures and Labels. The migration file for Labels is
class CreateLabelsTable extends Migration {
public function up() {
Schema::create('labels', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name', 128);
$table->enum('type', [ 'text' , 'contact' ]);
$table->timestamps();
});
}
public function down() {
Schema::dropIfExists('labels');
}
}
Within the model for Picture I defined
class Picture extends Model {
public function labels() {
return $this->belongsToMany('App\Label')
->withTimestamps();
}
}
Within the controller I can now use the following PHP code
$ptrPicture = Picture::findorfail(3); // '3' is an example of an id here
return response()->json($ptrPicture->labels()->pluck('id')->toArray());
which for example results in [5, 6, 9] for the ids of the Labels which are connected to Picture(3). This works nicely but now I don't want to return the ids of the Label only, but all the columns for the Label. How do I manage to get something returned like the following with Laravel?
[
{ id: 5, name: 'foo', type: 'text' },
{ id: 6, name: 'bar', type: 'text' },
{ id: 9, name: 'etc', type: 'contact' }
]
With pluck I can only return one of the columns? How do I return all three columns?
UPON REQUEST ... here are my other migration files:
class CreatePicturesTable extends Migration {
public function up() {
Schema::create('pictures', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('filename', 256);
$table->string('description', 4096)->nullable();
$table->timestamps();
});
}
public function down() {
Schema::dropIfExists('pictures');
}
}
class CreateLabelPictureTable extends Migration {
public function up() {
Schema::create('label_picture', function (Blueprint $table) {
$table->bigInteger('label_id')->unsigned();
$table->foreign('label_id')
->references('id')
->on('labels')
->onDelete('cascade');
$table->bigInteger('picture_id')->unsigned();
$table->foreign('picture_id')
->references('id')
->on('pictures')
->onDelete('cascade');
$table->timestamps();
});
}
public function down() {
Schema::dropIfExists('label_picture');
}
}
Either of the following will do the job.
$ptrPicture->labels->toArray(); // note the absence of brackets after 'labels'
// OR
$ptrPicture->labels()->get()->toArray();
Docs

Laravel implementing belongsTo one product for one or some category

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..

Laravel 5.2 - Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

This question has already been asked many times, I went through all the answers, but none solves the error I'm getting.
I'm using Laravel 5.2
I have 2 tables - Classifieds and Categories. When I want to create a classified, I get the error message:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (myclassified.classifieds, CONSTRAINT classifieds_category_id_foreign FOREIGN KEY (category_id) REFERENCES categories (id))
Migration files defined like this:
for classifieds table:
public function up()
{
Schema::create('classifieds', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('description');
$table->string('price');
$table->timestamps();
});
}
public function down()
{
Schema::drop('classifieds');
}
for categories table:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
public function down()
{
Schema::drop('categories');
}
and to add the foreign key,
public function up()
{
Schema::table('classifieds', function(Blueprint $table) {
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
});
}
public function down()
{
Schema::table('classifieds', function(Blueprint $table) {
$table->dropForeign('classifieds_category_id_foreign');
});
}
The Models are:
Classified model:
class Classified extends Model
{
protected $table = 'classifieds';
protected $fillable = ['title', 'category_id', 'description', 'price'];
protected $hidden = [];
public function category(){
return $this->belongsTo('App\Category');
}
}
and the Category model:
class Category extends Model
{
protected $table = 'categories';
protected $fillable = ['name'];
protected $hidden = [];
public function classifieds(){
return $this->hasMany('App\Classified');
}
}
and the store method in controller is defined like this:
public function store(Request $request)
{
$title = $request->input('title');
$category_id = $request->input('category_id');
$description = $request->input('description');
$price = $request->input('price');
Classified::create([
'title' => $this->title,
'category_id' => $this->category_id,
'description' => $this->description,
'price' => $this->price
]);
return \Redirect::route('classifieds.index')
->with('message', 'Ad created');
}
What is my mistake in database set up?
This happens, when you are trying to save Classified and assign the foreign key with an id of category that does not exist yet in Category table.
If you don't have the foreign ID yet, just leave it to be null and make sure you do this on migration to allow null values;
public function up()
{
Schema::table('classifieds', function(Blueprint $table) {
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('set null');
});
}
public function down()
{
Schema::table('classifieds', function(Blueprint $table) {
$table->dropForeign('classifieds_category_id_foreign');
});
}

laravel many to many fetching data

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

Categories