Error 500 with save() method of eloquent/laravel - php

I want to save an object with Laravel's eloquent but I get error 500 when trying to save.
This is my model code:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Categorie extends Model
{
}
and this is my action:
public function addCategorie() {
$input = Input::all();
$categorie = new Categorie;
$categorie->libelle = $input['label'];
$categorie->save();
return $categorie;
}
When I use print_r($categorie) after the save method I get a result, but when I use the save() method I got this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in 'field list' (SQL: insert into `categories` (`libelle`, `description`, `updated_at`, `created_at`) values (sss, zzz, 2015-12-23 16:20:30, 2015-12-23 16:20:30 ))

In your migration file for categories table, you need to have
Schema::create("categories", function($table){
// Id, name, etc
$table->timestamps();
}
so that eloquent queries can update when this entry was created and saved, or created_at and updated_at. If you don't want to use these timestamps, add
class Categorie extends Model {
public $timestamps = false;
}
to your Categorie model.

Related

Why my relation in Laravel are working backwards when I try to get an one to one associated value?

I got this error
Facade\Ignition\Exceptions\ViewException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'categories.product_id' in 'where clause' (SQL: select * from `categories` where `categories`.`product_id` = 2 and `categories`.`product_id` is not null limit 1) (View: /home/osboxes/shakira/resources/views/products/index.blade.php)
But my models and migrations are just fine. I have to erase migrations also from the database table and yes, I have my category_id in the produc table.
I'm trying to show the category in the index view.
Please share your information completely so people can understand and help you.
I guess you defined your relation backward in your models.
They should be like this:
class Product extends Model
{
public function category()
{
return $this->belongsTo(Product::class);
}
}
class Category extends Model
{
public function products()
{
return $this->hasMany(Category::class);
}
}

SQLSTATE[HY000]: General error: 1364 Field 'contactId' doesn't have a default value

On my model (Customer) I have one required parameter: $contactId.
On executing Customer::create(['contactId' => $contactId]) I receive the following error:
"message": "SQLSTATE[HY000]: General error: 1364 Field 'contactId' doesn't have a default value (SQL: insert into customers (updated_at, created_at) values (2019-12-10 12:33:46, 2019-12-10 12:33:46))"
The contactId field is nowhere to be found on in the insert statement. The value of contactId is set to 4, which corresponds to the correct value in the database through a FK.
The migration for the Customer table:
`Schema::create('customers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));
$table->bigInteger('contactId')->unsigned();
$table->foreign('contactId', 'FK_customer_contactId_contact_id')
->references('id')
->on('contacts');
});`
What's preventing Eloquent from creating the correct insert statement here? I've triple checked the spelling of contactId throughout the flow and in the database.
When I manually insert a row into customers, I have no issues retrieving the data and the contact-relation.
Thanks for your time!
Make contactId $fillable in Customer model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
protected $fillable = ['contactId'];
}
If you use create method to save data in to database so you must have to write this fillable property in your model
<?php
class Customer extends Model
{
protected $fillable = ['contactId'];
}
Make contactId $fillable in model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
protected $fillable = ['contactId'];
}
or
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
protected $guarded = [];
}

how to create a query with multiple tables in laravel

i want to create a query with multiple tables
the query that i need is:
SELECT orders.user_id, orderitem.product_id, orderitem.orderItem_quantity, product.product_price, product.product_imgPath,product.product_name
FROM orderitem, orders, product, users
WHERE orders.user_id = '$_Session[user_id]'
AND orderitem.product_id = product.product_id
AND orderitem.order_id = orders.order_id
AND orders.order_status = 1
and i try these codes:
1:
$cartProducts = DB::table('orderitem')
->join('product','product.product_id','=','orderitem.product_id')
->join('orders','orders.order_id','=','orderitem.order_id')
->where('orders.order_status','=','Waiting')
->where('orders.user_id','=',$userId)
->select('orderitem.*','orders.*','product.*','users.*')
->get();
The error that i get is:
SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'users'
2:
$cartProducts = DB::table('orderitem','orders','products','users')
->select('orderitem.*','orders.*','products.*','users.*')
->where('orders.user_id','=',$userId)
->where('orderitem.product_id','=','product.product_id')
->where('orderitem.order_id','=','orders_id')
->where('order_status','=','Waiting')
->get();
The error that i get is:
SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'orders'
And i know that i can't use multiple parameter for table function
Use laravel relationships https://laravel.com/docs/5.5/eloquent-relationships#one-to-many
First, in your User model do:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function images()
{
return $this->hasMany('App\Images'); //make sure your images table has user_id column
}
}
And then in your Image table model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
Now in your controller:
$data = App\Post::user(1)->with('images');
return view('view_name', ["data" => $data]);
Your view:
#foreach($data->images as $image)
<img src="{{ $image->url }}">
#endforeach

Laravel Eloquent still throwing error with updated_at column even I ignored it

I am developing a website using Laravel 5.2. I am working with database. So I used Laravel eloquent model to make the code neat and clean. But one of my Eloquent is throwing unknown updated_at column exception even if I already ignored it.
I ignored or override the built in function like this in my Entity.
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
//
protected $fillable = ['name', 'mm_name'];
public function setUpdatedAt($value)
{
// Do nothing.
}
public function setCreatedAt($value)
{
// Do nothing.
}
}
I deleted updated_at column from categories table. So if I update the category, updated_at column should be ignored.
So updated like this
function updateCategory($bag)
{
$category = Category::find($bag->id);
if($category)
{
$category->name = $bag->name;
$category->mm_name = (empty($bag->mm_name))?$bag->name:$bag->mm_name;
$category->save();
}
}
But it still throwing this error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in 'field list' (SQL: update `categories` set `name` = sdsd, `mm_name` = sdsd, `updated_at` = 2016-02-20 11:36:41 where `id` = 4)
I overrode the other tables and eloquent entity like that. That is all working, but this one is not. How can I fix that?
This is the screenshot of categories table:
If you're not using the created_at or updated_at fields, you need to set the $timestamps property on your model to false. Additionally, you don't need to override the setUpdatedAt() or setCreatedAt() methods.
class Category extends Model
{
protected $fillable = ['name', 'mm_name'];
public $timestamps = false;
}
If $timestamps is true, the Eloquent query builder will add in the updated_at field whenever you update a model.
Your mutator defination is wrong. it should be setUpdatedAtAttribute
and setCreatedAtAttribute
There was no need to delete the updated_at and deleted_at attributes from the database.
You have deleted the attributes from the database so there is no need for setUpdatedAtAttribute and setCreatedAtAttribute in your model. Laravel will include them as columns in your database.
Will advice you recreate the updated_at and created_at in the categories table and if you are using mysql 5.7 ensure that your timestamps are not 00-00-00 00:00:00 that is if you are manually created them(not recommended to manually create them).

Getting to use Eloquent hasMany() relationship

I have a table of categories in which my categories and their title and thumbnails are stored.
I have another table in which images are stored.
The third table is a joint table. I store in each record of it, the id of the image and the id of the category.
Table Schema:
id
cat_id
item_id
Now I want to get a cat_id by query_string and then pass it to the function for it to get the list of all images with this category in the database.
I'm confused about how to write the method. I have written the following method for CategoryList model which throws error:
class CategoryList extends Eloquent
{
protected $table = "categories_list";
function Images ()
{
return $this->hasMany("Image", 'id');
}
}
And here is the usage in the Image model:
return CategoryList::Images()->where("cat_id", '=', $catid)->get()->toArray();
But it throws the following error:
{"error":{"type":"Illuminate\\Database\\QueryException","message":"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'cat_id' in 'where clause' (SQL: select * from `images` where `images`.`id` is null and `cat_id` = 19)","file":"C:\\wamp\\www\\aone\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php","line":539}}
class Category extends Eloquent {
public function images()
{
return $this->belongsToMany('Image');
}
}
Then do:
$images= Categorie::find($catid)->images;
In this case, your pivot table is 'category_image', but if you need to choose another name, it must be specified
return $this->belongsToMany('Image', 'your_pivot_table_name', 'cat_id', 'item_id');
Please visit http://laravel.com/docs/eloquent#many-to-many for more information

Categories