Laravel: Column 'category_slug' cannot be null - php

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'category_slug' cannot be null (SQL: update products set category_slug = ?, products.updated_at = 2022-12-23 12:06:26 where id = 1)
How I get product category_slug colmun from category slug table.
Categories Table:
|id|name|slug |
|4 |Cat4|cat-4|
|5 |Cat5|cat-5|
|6 |Cat6|cat-6|
Products Table
|id|name|category_id|category_slug|
|1 |USDT|4 |cat-4 |
|2 |BTCH|5 |cat-5 |
|3 |EURT|6 |cat-6 |
Product Controller (Update Method)
public function update(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:190',
'price' => 'required',
'category_id' => 'required',
])->validate();
$code=Product::find($request->id);
$code->name=$request->name;
$code->category_id=$request->category_id;
$code->category_slug=$request->category_slug;
$code->update();
return redirect()->back()->with('success',__('Product has been updated'));
}
`
Product Model
`
class Product extends Model
{
use HasFactory;
public function category()
{
return $this->hasOne(Category::class,'id','category_id');
}
`
I GET THIS ERROR
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'category_slug' cannot be null (SQL: update products set category_slug = ?, products.updated_at = 2022-12-23 12:06:26 where id = 1)

I think you should not add the category_slug to your products table
you already have all the information you need about the product's category when you added the category_id to the products table
to get the category_slug from the product
you can do something like this
Product::with('category')->find(1)->category->slug

The problem lies here :
$code->category_slug=$request->category_slug;
It seems that $request->category_slug is null/undefined. If you are sure sending it from the frontend via an input make sure it has the right name attribute name="category_slug"
If however, you don't send it from frontend you should use slug helper to generate it from a string you chose, example:
$code->category_slug= \Str::slug($request->name . '-' .$request->category_id);
This will generate a slug from the name and id combined.
EDIT: If you want to get the current Product category slug you can use it like so:
$code->category_slug=$code->category->category_slug;
You might need to use $code->save() instead of update()

Change your migration.
public function up()
{
Schema::table('products', function (Blueprint $table) {
$table->string('category_slug')->nullable()->change();
});
}
It seems that you are not sending any value to the category_slug column while updating the record. The column must have a nullable constraint.

Related

relations with 4 tables in laravel

I have four tables as follows.
Services_cats
Session_pat
Invoice_item
Invoice
id
id
id
id
name
services_cat_id
service_id
code
patient_id
invoice_id
discount
I need to have relations among them with one Eloquent query in Laravel. Below is what I have reached so far; I used many-to-many relations in the invoice table.
public function invoice_item()
{
return $this->belongsToMany(Session_pat::class, 'invoice_items', "invoice_id",
"service_id", "id", "id");
}
And I used this code to access the four tables.
$status4 = Invoice::select('id')->with(['invoice_item' => function ($q){
$q->select('id', 'services_cat_id')
->with(['service_cat' => function ($q) {$q->select('id as myid', 'name');}])
;}])
->where('id', 122)->get();
but I get this error
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in
field list is ambiguous (SQL: select id, services_cat_id,
invoice_items.invoice_id as pivot_invoice_id,
invoice_items.service_id as pivot_service_id from session_pats
inner join invoice_items on session_pats.id =
invoice_items.service_id where invoice_items.invoice_id in
(122) order by id desc)
You Should Specific The Table Name, WHen Using Same Column Name In Query.
Rule: tableName.column EX: invoiceTable.id
$status4 = Invoice::select('TableName.id')->with(['invoice_item' => function ($q){
$q->select('TableName.id', 'services_cat_id')
->with(['service_cat' => function ($q) {$q->select('TableName.id as myid', 'name');}])
;}])
->where('TableName.id', 122)->get();

How can I insert both ID of Two tables (Many to Many Relationship)

I have three table Category and Company and Company_category.
Company model
public function categories(){
return $this->belongsToMany(\App\Category::class);
}
Category model
public function companies(){
return $this->belongsToMany(Company::class,'company_category');
}
When I try Insert Company ID into table
CategoryController Code:
$category = new Category();
$category->companies()->sync($request->get('company_id'));
How can I insert category_id with company_id both at once
only this code return error :
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'category_id' cannot be null (SQL: insert into company_category (category_id, company_id) values (, 1))
Like #Stormhammer mentioned, you need to save the category first or else it does not have an id.
$category = new Category();
$category->save();
$category->companies()->sync($request->get('company_id'));

Unable to Add Username to Post Author

I'm trying to insert the username for the author from the users table into the posts table, but it's not letting me. I'm using Backpack for my CRUD, and I'm not sure what I'm doing wrong. I'm also not sure as to why the ID is appearing for the username instead of the username itself, as the correct username(s) are appearing in the select box. I am getting the following error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails (idf.posts,
CONSTRAINT posts_author_foreign FOREIGN KEY (author) REFERENCES
users (username)) (SQL: insert into posts (title, content,
author, updated_at, created_at) values (aasdasd, asdasda,
1, 2018-12-24 04:25:23, 2018-12-24 04:25:23))
I'm running SQL 8, Laravel 5.7, and PHP 7.1.19. So far I've tried clearing the cache via the artisan command and performing a migrate:refresh (which is fine because I have no legitimate data).
In App\Models\Post:
protected $table = 'posts';
protected $primaryKey = 'id';
protected $foreignKey = 'author';
public $timestamps = true;
protected $guarded = ['id'];
protected $fillable = [
'title', 'content', 'author'
];
protected $hidden = [];
protected $dates = [];
public function user()
{
return $this->hasOne('App\Models\User');
}
Posts Table Creation:
Schema::create('posts', function (Blueprint $table) {
$table->increments('id')->unique();
$table->string('title')->required();
$table->longtext('content')->required();
$table->string('author');
$table->foreign('author')->references('username')->on('users');
$table->timestamps();
});
Select Box on PostCrudController:
$this->crud->addField([
'label' => "Author",
'type' => 'select2',
'name' => 'author', // the db column for the foreign key
'entity' => 'user', // the method that defines the relationship in your Model
'attribute' => 'username', // foreign key attribute that is shown to user
'model' => "App\Models\User", // foreign key model
'options' => (function ($query) { //limit to only admins
return $query->orderBy('username', 'ASC')->where('admin', 1)->get();
}),
]);
In all, I just need to allow the username from the select dropdown to be inserted into the author column, which would be the username for the user itself.
What I understood from your problem is that you are trying to add a relation between your posts table and users.
So from my point of view, instead of using foreign migration like
$table->foreign('author')->references('username')->on('users');
you should make the foreign key like this
$table->unsignedInteger('user_id')
$table->foreign('user_id')
->references('id')
->on('users')
->onUpdate('CASCADE')
->onDelete('CASCADE');
And then you can pass the id of the user in the user_id column to establish the relationship between these two.
The benefits of using the foreign key like this are
The id column is a primary key in users table so it will uniquely Identify your user
and it is an unsigned integer so it will be easy for the SQL engine to index this.
Now for fatching your data you can definitely the following eloquent relation in your Post model
public function user() {
return $this->belongsTo('App/User');
}
And while fatching posts you can use eager loading (with() eloquent method) something like
$posts = Post:::with('user)->get();
Now with all of the posts you can access any associated user information for example:
forach ($posts as $post){
$userName = $post->user->name;
}
Hope this will help.

Laravel 4,eloquent mysql table design issue

I want to be able to design a database which has the following;
customer
--------------
id(int) | name
Company
-------------------------
id(int) | name | location
queue
--------------------------------------------------------------------------------
id (datetime-primary but not auto-increment) | company_id | customer_id | position (not primary but auto-increment)
customer_queue
-----------------------
customer_id | queue_id
public function up()
{
Schema::create('queues', function(Blueprint $table)
{
$table->dateTime('id')->primary(); //dateTime for id since one is genereated every other working day
$table->integer('company_id')->unsigned();
$table->foreign('company_id')->references('id')->on('companies');
$table->integer('customer_id')->unsigned();
$table->foreign('customer_id')->references('id')->on('customers');
$table->increments('position');
$table->time('start_time');
$table->time('end_start');
$table->integer('type');
$table->time('joined_at');
$table->time('left_at');
$table->integer('customer_queue_status');
$table->timestamps();
//$table->primary(array('id', 'position'));
});
//find a way to make position auto-increment without being primary and rather set id to primary without auto-incrementing
}
I'm using laravel 4 with eloquent and it doesn't allow me to specify only primary for id in queue table and then make position auto-increment without being primary.
The error i get is as follows
>This is the error i get
>[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1068 Multiple primary ke
y defined (SQL: alter table `queues` add primary key queues_id_primary(`id`
))
Increments will automatically try to set the field as a primary key. Therefore you can not use it to increment your position automatically.
If your id field is set to primary, it is by definition unique.
I think there is no way around implementing the auto-increment on your own.
I would do it in some way like this, in your Queue model:
class Queue extends Eloquent {
//....
public static function boot() {
parent::boot();
static::creating(function($queue) {
$position = DB::table('queues')->max('position');
if(is_null($position)) $position = 0;
$position++;
$queue->position = $position;
return true;
});
}
//....
}
This way everytime you save your Queue model it should look for the highest value and increment that by one. In case you have no entry yet it will start with 1.
In your schema, set $table->integer('position')->unique();

Laravel base table not found using pivot model

Hi im trying to query my tasks table. A little background information on the tables and how they are related.
Users, create Projects and Tasks, Statuses for projects and tasks can be selected from the status table, users make their own, i plan to have default ones but users may want to create their own.
By default i want to find all the users tasks where the status_name which is held in the statuses table does not equal closed. I decided it would be best to actually create a table called task_status which holds the task_id as well as the status_id. I still want to find the logged in users tasks and then find the status name based on the status_id held in the tasks table, which can be referenced in the statuses table. I then want to only display the any records not equal to closed but the first part which is explained below is trickier than first anticipated.
My table structures can be found below:
Table structure
Users
id | username | email
Tasks
id | user_id | client_id | project_id | status_id | task_name | task_brief
Statuses
id | status_name
Projects
id | user_id | client_id | status_id | type_id | project_name | project_brief
task_status
id | user_id | task_id | status_id
I'm trying to query my db simply first so that I can be sure that the data returned is correct. So I've changed my query to the below:
$user = User::with(array('tasks', 'task.status', 'tasks.taskstatus',
'tasks.clients'))->find(Auth::user()->id);
and I'm trying to return as follows (please bear in mind I also want to query the status table so that I am able to return the name of the status):
#foreach($user->tasks as $task)
{{ $task->task_name }}
#if(!is_null($task->clients))
{{ $task->clients->client_code }}
#endif
#if(!is_null($task->taskstatus))
{{ $task->taskstatus->status_name }}
#endif
#endforeach
My models:
Task.php
public function status(){
return $this->hasOne('Status', 'status_id');
}
public function taskstatus() {
return $this->hasMany('TaskStatus', 'status_id');
}
Status.php
public function tasks()
{
return $this->hasMany('Task');
}
public function taskstatus()
{
return $this->hasMany('TaskStatus', 'status_id');
}
TaskStatus.php
public function tasks()
{
return $this->hasMany('Task', 'task_id');
}
public function status() {
return $this->belongsTo('Status', 'status_id')
}
However using the above returns the following error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'imanage.task_statuses' doesn't exist (SQL: select * from `task_statuses`
where `task_statuses`.`status_id` in (?, ?, ?, ?, ?, ?, ?))
(Bindings: array ( 0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 5, 5 => 6, 6 => 7, ))
I'm sure that its my relationships that are defined incorrectly but I am not sure how to correct these.Can anyone help?
You can also try this code:
$user = User::whereHas('task.status', function($q)
{
$q->where('status', '!=', 'close');
})
->with('task', 'task.clients')
->where('id', Auth::user()->id)
->first();
Check the eloquent docs on querying relationships.
also remember DO NOT ECHO VIEW, return the view instead.
The error seems related to the fact that Laravel (well, actually Eloquent) is getting the wrong table name: below you have task_statuses instead of task_status. Remember that Eloquent will attempt to pluralize named models to get the table name.
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'imanage.task_statuses' doesn't exist
So either rename your table to match Laravel expectations, or in your model specify a custom table name:
class TaskStatus extends Eloquent {
protected $table = 'task_status';
...
Additionally, this part of your code is unclear to me:
Task.php
public function status(){
return $this->hasOne('Status', 'status_id');
}
public function taskstatus() {
return $this->hasMany('TaskStatus', 'status_id');
}
Does your Task have one status, or does it have many statuses?

Categories