I am doing project in Laravel. I have used laravel's eloquent model. I want to insert record into the database with timestamp values.
Here is my model 'Provider.php'
{
protected $primaryKey = 'provider_id';
protected $table = 'provider';
protected $fillable = [
'organization_name',
'email',
'website',
'mobile',
'landline',
'password',
'added_by'
];
public function cities(){
return $this->belongsToMany('App\City','provider_city','provider_id','city_id');
}
}
'City.php'
{
protected $primaryKey = 'city_id';
protected $table = 'city';
protected $fillable = ['state_id','name'];
}
and my controller method is as following,
{
$city_selection = $request->input('city_selection');
$provider = Provider::findOrFail($provider_id);
foreach ($city_selection as $city) {
$provider->cities()->attach($city['city_id']);
}
}
where city_selection is as below,
"city_selection":
[
{
"city_id": 1,
"name": "Pune"
},
{
"city_id": 3,
"name": "Bangalore"
}
]
After that when I tried to insert the record then all fileds i.e. provider_id and city_id filed goes properly into the database but the only problem is created_at and updated_at fields are still null.
I have used timpstamps(); while creating migration file. I don't know what's going wrong.
Any suggestions?
You need to add the dates mutators.
https://laravel.com/docs/5.3/eloquent-mutators#date-mutators
class Provider extends Model
{
/**
* The attributes that should be mutated to dates.
*
* #var array
*/
protected $dates = [
'created_at',
'updated_at',
'deleted_at'
];
}
Add timestamp in your Schema
$table->timestamps();
Your schema look like this
Schema::create('city', function(Blueprint $table){
$table->increments('id');
$table->integer('state_id')->unsigned();
$table->foreign('state_id')->references('id')->on('state');
$table->string('name', 100);
$table->timestamps();
});
Add following columns in your table schema.
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));
created_at column will store value when record is inserted and updated_at will keep updated when any changes in this record(Any update in row).
Update
Use below code to update in new migration
public function up()
{
Schema::table('table_name', function($table) {
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));
});
}
Related
I am beginner. I have small problem with Laravel Equolent.
I have migrations:
Schema::create('datas', function (Blueprint $table) {
$table->id();
$table->integer('number');
$table->timestamps();
});
and model:
class Data extends Model
{
protected $guarded = ['id'];
protected $fillable = [
'number'
];
protected $dates = [
'created_at',
'updated_at',
'date'
];
protected $casts = [
'number'=>'integer',
];
}
Normalny I make this code:
Data::get();
and this is return me all record from DB.
I need information how often does the number appear in the database.
For example:
Data->where('number', 1)->get();
Data->where('number', 15)->get();
Data->where('number', 55)->get();
etc
how wany can I count this result? ->count()?
If you need to count all the records in your Data model, you can use this code:
$count = Data::count();
But if you want to count specific number, try this:
$count = Data::where('number', $number)->count();
in the controller file Data::count();
I have a model hotel.php to insert hotel data.insert data using create() but it dosen't return id, the returning collection hasn't id field!
Controller.php
/** "/user/2/create" */
public function store(User $user, HotelRequest $request)
{
$slug = (new hotel)->uniqueSlug( $request->name );
$request->merge([
'cat_id' => 1,
'slug' => $slug,
'created_by' => auth()->user()->id,
]);
$hotel = $user->hotels()->create( $request->all() );
dd($hotel);
................
hotel.php (model)
namespace App;
use Illuminate\Http\UploadedFile;
use Illuminate\Database\Eloquent\Model;
class hotel extends Model
{
protected $fillable = ['name', 'description','address','street','city','email',
'phone','web','cat_id','slug','created_by'];
protected $primaryKey = 'slug';
/**
unique slugs genarating
*/
protected $slug_guards = ['create','room'];
public $incrementing = false;
User.php (model)
public function hotels( )
{
return $this->hasmany('App\Hotel');
}
and the final result
It dosen't have id attribute. I need id to upload image!
NB: I changed that primarykey to default 'id' but no change in result.
Create_hotels... migration
public function up()
{
Schema::create('hotels', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->integer('created_by');
$table->integer('cat_id');
$table->string('name');
Your hotel model set the primary key as the slug :
protected $primaryKey = 'slug';
What i usually do, is for all my migrations, i set an autoincrements like following :
$table->increments('id');
this way laravel handles everything for you. Each create, update or whatever method handle the id of your items.
With this, you can then return the id of a stored data this way :
$id = create($data)->id;
where $data is your model with new datas. $id should now contain the id value of the newest stored model datas.
You have to change the Hotel model (or remove the whole line):
public $incrementing = true;
You are dumping the data you just inserted into the db which does not contain a id field.
create a show method in your Controller class as follows
public function show(User $user){
dd($user)
}
with a route as follows:
Route::get('user/{user}', 'Controller#show')
In hotel.php before the protected $fillable declaration try adding
protected $guarded = [
'id',
];
In your controllers store() method just after $slug = (new hotel)->uniqueSlug( $request->name );
try adding a $slug->save(); then returned slug should have an ID returned with it.
and/or possible the same similar strategy after line
$hotel = $user->hotels()->create( $request->all() );
by adding $hotel->save();
I changed the primarykey to default id and $incrementing = true; now its returning id of the created data. I changed whole methodes in Controller
As you can see on the following image my laravel relation between shoporder and shoporderroutingstepplans is not as it has to be.
I have no idea what I exactly did wrong so I hope someone can help me out. In the code beneath I have left some fields out of the code to make it more legible.
class shoporder extends Model
{
protected $primaryKey = 'ID';
protected $fillable = [
'CADDrawingURL',
'ID',
'Costcenter',
'CostcenterDescription',
'Costunit',
'CostunitDescription',
'Created',
'Creator',
'CreatorFullName',
'Description',
'ShopOrderParent',
'ShopOrderParentNumber',
'ShopOrderRoutingStepPlanCount',
'Status',
'SubShopOrderCount',
];
public function shopOrderRoutingStepPlans() {
return $this->hasMany('App\shopOrderRoutingStepPlan', 'ShopOrder', 'ID');
}
}
class ShopOrderRoutingStepPlan extends Model
{
protected $primaryKey = 'ID';
public $table = "shoporderroutingstepplans";
protected $fillable = [
'Account',
'ID',
'AccountName',
'AccountNumber',
'AttendedPercentage',
'Backflush',
'Created',
'Creator',
'CreatorFullName',
'Description',
'ShopOrder',
];
public function shopOrder() {
return $this->belongsTo('App\shopOrder', 'ShopOrder', 'ID');
}
}
This is the code Im executing to get the relations of 1 shoporder in the controller.
$orders = shopOrder::find('0600959e-6b92-4135-8ea8-1fa2fd92a916')->shopOrderRoutingStepPlans()->get();
In the shoporder migration I defined the primary key:
$table->string('ID')->unique();
$table->primary('ID');
In the shoporderroutingstepplans migration I defined the foreign key as followed.
$table->string('ID')->unique();
$table->primary('ID');
$table->foreign('ShopOrder')
->references('ID')
->on('shoporders');
You must switch the order of the last two parameters:
From
return $this->hasMany('App\shopOrderRoutingStepPlan', 'ShopOrder', 'ID');
To
return $this->hasMany('App\shopOrderRoutingStepPlan', 'ID', 'ShopOrder');
The parameters are
model,
name of column in the linked model,
name of column in this model.
I have two tables :
1) users
Schema::create('users', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->string('id')->unique();
$table->string('name')->nullable();
$table->string('surname')->nullable();
$table->string('email')->unique()->nullable();
$table->string('address')->nullable();
$table->string('telephone')->nullable();
$table->timestamps();
});
2) users_games
Schema::create('user_games', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->increments('id');
$table->string('user_id');
$table->boolean('state')->default(false);
$table->timestamps();
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
});
Every user can have many games so i want every game->user_id to match with the user's id.
I have the below function where i create a user :
public function createNewUser(){
// Check here if user is about to win,
$mUniqueID = uniqid("",true); // create an id
$user = new User();
$user->id = $mUniqueID;
$saved = $user->save();
$user = User::find($mUniqueID);
$currentGame = new UserGame(['state' => false]); // It is in 'fillable' array - boolean
$user->games()->save($currentGame);
$mUserInformation = [
'mUniqueID' => $mUniqueID,
'game_id' => $user->games()->latest()->first(),
];
if($saved)
return $mUserInformation;
else
return redirect()->route('game');
}
The error i get :
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails
(db_name.user_games, CONSTRAINT user_games_user_id_foreign
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE)
(SQL: insert into user_games (state, user_id, updated_at,
created_at) values (0, 59380, 2017-06-07 14:18:52, 2017-06-07
14:18:52))
I can't understand why this error occurs. If you need any more information please ask and i will provide.
EDIT 1 :
Also, in my database an id of user is : 59380b495c1942.30562655 but the error mentions only 59380, shouldn't it be 59380b495c1942.30562655 ?
EDIT 2:
User.php model
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
// all fillables here
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function games()
{
return $this->hasMany('App\UserGame');
}
}
UserGame.php model
class UserGame extends Model
{
protected $fillable = [
'state'
];
public function user()
{
return $this->belongsTo('App\User');
}
}
So if you want to use InnoDB engine in /config/database.php change 'engine' => null, to 'engine' => 'InnoDB'
To use uuid you can add laravel-uuid by add composer require webpatser/laravel-uuid, after add the aliases in config/app.php
Change Migrations $table->increments('id') to $table->uuid('id') and add $table->primary('id')
In models add public $incrementing = false; Hope help you
In the end add trait
namespace App;
use Webpatser\Uuid\Uuid;
trait Uuids
{
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->{$model->getKeyName()} = Uuid::generate()->string;
});
}
}
In model also add use Uuids;
Hi laravel is not inserting correct value in pivot table for many to many case.
Here my first model is
class ShippingAddress extends Eloquent {
protected $guarded = array('id');
protected $table = 'shippingAddress';
public function mwsOrder()
{
return $this->belongsToMany('MwsOrder',
'mwsOrders_shippingAddress',
'Address_id',
'AmazonOrderId'
);
}
}
Second Model is
class MwsOrder extends Eloquent {
protected $table = 'mwsOrders';
protected $primaryKey = 'AmazonOrderId';
public function shippAddress()
{
return $this->belongsToMany('ShippingAddress',
'mwsOrders_shippingAddress',
'AmazonOrderId',
'Address_id'
);
}
}
EER Diagram
Now when i run this
$mwsOrder = new MwsOrder;
$mwsOrder->AmazonOrderId = 'Eve 6';
$mwsOrder->save();
$address = new ShippingAddress;
$address->name = 'Naruto Uzumaki';
$address->save();
$address->mwsOrder()->attach($mwsOrder);
//$mwsOrder->shippAddress()->save($address);
laravel throws error and this is what laravel trying to run the query
(SQL: insert into mwsOrders_shippingAddress (Address_id,
AmazonOrderId) values (1, 3))
What i need is to generate this query
insert into mwsOrders_shippingAddress (Address_id,
AmazonOrderId) values (1, 'Eve 6')
Update:
Schema are:
Schema::create("shippingAddress", function(Blueprint $table)
{
$table->increments("id");
$table->string("Name");
$table->timestamps();
});
Schema::create("mwsOrders", function(Blueprint $table)
{
$table->increments("id");
$table->string("AmazonOrderId")->unique();
$table->timestamps();
});
Schema::create("mwsOrders_shippingAddress", function(Blueprint $table)
{
$table->increments("id");
$table->string("AmazonOrderId");
$table->foreign("AmazonOrderId")->references("AmazonOrderId")->on('mwsOrders');
$table->integer("shipping_address_id")->unsigned();
$table->foreign("shipping_address_id")->references('id')->on('shippingAddress');
$table->timestamps();
});
At first change the shippAddress to this:
// Specify the primary key because it's not conventional id
protected $primaryKey = 'AmazonOrderId';
public function shippAddress()
{
return $this->belongsToMany('ShippingAddress',
'mwsOrders_shippingAddress',
'AmazonOrderId',
'Address_id'
);
}
Then you may try this:
$mwsOrder = new MwsOrder;
$mwsOrder->AmazonOrderId = 'Eve 6';
$mwsOrder->save();
$address = new ShippingAddress(['name' => 'Naruto Uzumaki']);
$mwsOrder->shippAddress()->save($address); // Save and Attach