Laravel Trailing Data Exception when model save or update - php

I have problem with update the model data in laravel 5.6,
After many time I find that actually problem is with created_at and updated_at.
My code:
$editStuState = StuAtt::where('studentId' , '=' , 1007)->first();
dd($editStuState -> created_at);
and dd($editStuState)
StuAtt {#382 ▼
#table: "stu_attendance"
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:7 [▼
"id" => "3"
"studentId" => "1007"
"present" => "7"
"absent" => "2"
"leave" => "6"
"created_at" => "2018-04-19 07:01:19.929554"
"updated_at" => "2018-04-19 02:31:19.000000"
]
#original: array:7 [▼
"id" => "3"
"studentId" => "1007"
"present" => "7"
"absent" => "2"
"leave" => "6"
"created_at" => "2018-04-19 07:01:19.929554"
"updated_at" => "2018-04-19 02:31:19.000000"
]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
Error that appears when I print the created_at field:
InvalidArgumentException
Trailing data
Where is mistake and how fix it?

Trailing data is a Carbon error, it's because you probably use PostgreSQL, and DB's date returns milliseconds.
"created_at" => "2018-04-19 07:01:19.929554"
You can add the following method to your (base) model.
// ...
public function getDateFormat()
{
return 'Y-m-d H:i:s.u';
}
}

Related

Storing attributes of a multiple models, to single array in laravel

I have the following eloquent in my controller,
$getJobs=JobTitle::where('department_id',DepartmentUser::where('user_id', $user->id)->first()->department_id)->get();
This gives me following collection
Illuminate\Database\Eloquent\Collection {#2970 ▼
#items: array:3 [▼
0 => App\JobTitle {#2967 ▶}
1 => App\JobTitle {#2968 ▶}
2 => App\JobTitle {#2962 ▶}
]
#escapeWhenCastingToString: false
}
And one model element looks like this
1 => App\JobTitle {#2968 ▼
#connection: "mysql"
#table: "job_titles"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#escapeWhenCastingToString: false
#attributes: array:9 [▼
"id" => 898
"title" => "driver"
"company_id" => 635
"department_id" => 252
"created_by" => null
"created_at" => "2022-04-20 05:30:38"
"updated_at" => "2022-04-20 05:30:38"
"deleted_at" => null
"archived_at" => null
]
#original: array:9 [▶]
#changes: []
#casts: array:2 [▶]
#classCastCache: []
#attributeCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: array:3 [▶]
#guarded: array:1 [▶]
+archives: true
#forceDeleting: false
}
Now I want to store all the job title (title) value's into single array
"title" => "driver"
In the above scenario, I have array elements and therefore I need store all three respective job titles to one single array...
$jobs = ['driver', 'chef', 'engineer'];
I tried adding an foreach, but it was giving me the following error,
#foreach ($getJobs as $getJob)
dd ($getJob->title);
#endforeach
ParseError syntax error, unexpected token "foreach"
What is the best way to achieve this?
You can simply loop on $getJobs and collect the title names in an array like below:
<?php
$getJobs = JobTitle::where('department_id',DepartmentUser::where('user_id', $user->id)->first()->department_id)->get();
$titles = [];
foreach($getJobs as $job){
$titles[] = $job->title;
}
dd($titles);

How to Foreach loop through Laravel collection.?

i m a beginner at laravel. using 5.5 . i have this collection return by my controller :
$products = Product::with('bazar.resellers')->take(2)->get();
dd($products);
//return view('shop.index')->with('products', $products);
which basically is three tables with nested relations. Note the relations lists in the code below. i want to access data(all columns in red colour) from every model i have in the collection i.e. Product, bazar and reseller.
Relationships are quite fine. but how to retrieve it from a collection? i dunno how foreach loops play with a collection.
Collection {#578 ▼
#items: array:2 [▼
0 => Product {#487 ▼
#fillable: array:7 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:10 [▼
"id" => 1
"created_at" => "2018-04-27 12:54:41"
"updated_at" => "2018-04-27 12:54:41"
"imgp" => "shirt.jpg"
"title" => "shirt1"
"Prod_descript" => "shirt1 is a good shirt"
"price" => 10
"reseller_id" => 1
"City_id" => 1
"bazar_id" => 1
]
#original: array:10 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼
"bazar" => Bazar {#523 ▼
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:7 [▼
"id" => 1
"Bazarname" => "Saddar"
"Bazarlat" => null
"Bazarlong" => null
"created_at" => null
"updated_at" => null
"City_id" => 1
]
#original: array:7 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼
"resellers" => Collection {#574 ▼
#items: array:1 [▼
0 => Reseller {#564 ▼
#guard: "reseller"
#fillable: array:12 [▶]
#hidden: array:2 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:15 [▼
"id" => 1
"Fname" => "talha"
"Lname" => "ali"
"email" => "p#g.com"
"password" => "$2y$10$M7wOmSouxSAYADN7NeFdSObT8fGwkEOFxVmOgcNSWvrixWCDtA/1S"
"mobile_no" => "03169880008"
"landline_no" => "0987654"
"shop_name" => "MyTestSHop"
"NIC_no" => "170178359437589754"
"shop_address" => "University Town, Peshawar, Pakistan"
"remember_token" => "wrb3nOwOWQcTuoF0P9KnaknwpOxfpTHt4gkShUmTzkR2Df9A7pPY5shBq6pQ"
"created_at" => "2018-04-27 12:42:25"
"updated_at" => "2018-04-27 12:42:25"
"City_id" => 1
"bazar_id" => 1
]
#original: array:15 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#visible: []
#guarded: array:1 [▶]
#rememberTokenName: "remember_token"
}
]
}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▼
0 => "*"
]
}
1 => Product {#488 ▶}
]
}
the code i have tried is not working!
#foreach($products as $product)
<h1>{{ $product->title }}</h1>
#foreach($product->bazar as $bazar)
<h3>{{ $bazar->Bazarname }}</h3>
#foreach($bazar->resellers as $reseller)
<p>{{ $reseller->Fname }}</p>
#endforeach
#endforeach
#endforeach
If product has single bazar,then you don't need to use foreach on $product->bazar. You just need to use bazar property directly. and if product has many bazars, then update your product model bazar() method like:
public function bazars()
{
return $this->hasMany(Bazar::class);
}
It returns collection of bazars and then you can run loop on that.

Getting list of discounted products in laravel

I try to get all of my discounted products in one page, but it doesn't return results
while the exact same query return results in homepage.
function
public function promotions() {
$promotions = Discount::with('products')->orderby('id', 'desc')->paginate(12);
return view('front.promotions', compact('promotions'));
}
route
Route::get('/promotions', 'frontend\FrontendController#promotions')->name('promotions');
blade
#foreach($promotions as $product)
{{$product->title}} // return nothing!
#endforeach
here is dd of my $product
dd code
Discount {#686 ▼
#table: "discounts"
#dates: array:2 [▶]
#fillable: array:4 [▶]
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:8 [▶]
#original: array:8 [▼
"id" => 4
"value_from" => "2018-02-18"
"value_to" => "2018-02-19"
"amount" => "10000"
"product_id" => 16
"stock" => 25
"created_at" => "2018-02-19 09:05:48"
"updated_at" => "2018-02-19 09:47:10"
]
#changes: []
#casts: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼
"products" => Product {#697 ▼
#fillable: array:16 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:23 [▶]
#original: array:23 [▼
"id" => 16
"title" => "new product"
"slug" => "new-product"
"imageOne" => "productone-1519001703.png"
"imageTwo" => "producttwo-1519001703.jpg"
"short_description" => """
<!DOCTYPE html>\r\n
<html>\r\n
<head>\r\n
</head>\r\n
<body>\r\n
<p>eagtheyh</p>\r\n
</body>\r\n
</html>
"""
"description" => """
<!DOCTYPE html>\r\n
<html>\r\n
<head>\r\n
</head>\r\n
<body>\r\n
<p>shw4 bw 6r uwrurjw ryt jyhkiuggk</p>\r\n
</body>\r\n
</html>
"""
"price" => "100000"
"meta_description" => "gjyrj"
"meta_tags" => "yrujr,ujrtsdjr,jrjurysj,"
"arrivalDays" => "1"
"height" => "546"
"weight" => "56"
"lenght" => "56"
"width" => "56"
"sku" => "47ghg"
"stock" => "24"
"status_id" => 1
"brand_id" => 1
"category_id" => 1
"subcategory_id" => 1
"created_at" => "2018-02-19 07:55:03"
"updated_at" => "2018-02-21 09:58:04"
]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
#slugOptions: null
#configSettings: array:4 [▶]
}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
You need to iterate over discounts and products:
#foreach($promotions as $discount)
{{ $discount->products->title }}
#endforeach

Database \ Eloquent \ MassAssignmentException fam

I try add data to databese. But have this error.
Illuminate \ Database \ Eloquent \ MassAssignmentException fam
'fam' is a name first argument.
Data dump:
array:8 [▼
"fam" => "6"
"im" => "e"
"ot" => "r"
"phone" => "e"
"log" => "e"
"pass" => "e"
"Регистрация" => null
"_token" => "bEJpcLPYWo5GmhW11Zxs8K0dMmN6anNsvuO0a492"
]
Function code:
$this->validate($request,[
'fam'=>'required|max:255',
'im'=>'required|max:255',
'ot'=>'required|max:255',
'log'=>'required|max:255',
'pass'=>'required|max:255',
'phone'=>'required|max:255',
'Регистрацияd'=>'require|max:255'
]);
$data=$request->all();
dump($data);
$user=new userModel;
dump($user);
$user->fill($data);
User Model dump:
userModel {#192 ▼
#filable: array:8 [▶]
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#attributes: []
#original: []
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▼
0 => "*"
]
}
And model code:
class userModel extends Model
{
protected $filable=['fam','im','ot','phone','login','pass','reg','token'];
}
You can see the structure of the database here:
enter image description here
Your model has no attributes, and it looks like you have a typo in $fillable
protected $filable=['fam','im','ot','phone','login','pass','reg','token'];

Laravel not adding data to foreign key column value in the database

I'm not getting an error message from this, but Laravel 5.1 will not assign values to a foreign key column in the OrderDetails table. I've tried multiple different calls and can't figure out what's wrong.
public function orderProduct(Request $request){
//Try and find the current incomplete order. If find fails, then create new order.
$order;
try{
$order = OrderHeader::where("UserID","=", Auth::user()->id)
->where('OrderCompleted', '=', false)->firstOrFail();
}catch(\Illuminate\Database\Eloquent\ModelNotFoundException $e){
$order = new OrderHeader;
//find user
$id = Auth::user()->id;
$user = User::find($id);
//associate user
$order->user()->associate($user);
//mark order incomplete
$order->OrderCompleted = false;
$order->OrdersShipped = false;
$order->save();
}
//find matching or create new order detail. Update or add details and ade it to order.
/**
*Somewhere in here is the problem(s)
*The four or so lines I've commented out are all different attempts
*to get the value in the database.
*/
$orderDetail;
$productID = $request->input("pID");
try{
$orderDetail = $order->orderDetails()->where("ProductID", "=", $productID)->firstOrFail();
//add feilds assignment
}catch(\Illuminate\Database\Eloquent\ModelNotFoundException $e){
$orderDetail = new OrderDetail;
// $orderDetail->orderHeader()->associate(OrderHeader::find($order->OrderID));
$orderDetail->QtyOrdered = $request->input("qty");
$orderDetail->product()->associate(Product::find($productID));
// $orderDetail->OrderHeaderID = $order->OrderID;
// $orderDetail->orderHeader()->associate($order);
// $orderDetail->save();
//$order->orderDetails()->save($orderDetail);
//$orderDetail = OrderDetail::create(['OrderHeaderID' => $order->OrderId,'ProductID'=> $request->input("pID"), 'QtyOrdered' => $request->input("qty")]);
}
return $orderDetail;
// ProductController::cartView($order);
}
The relationship bewtween OrderHeader and OrderDetails are as follows.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class OrderDetail extends Model
{
//
protected $table = "OrderDetails";
protected $primaryKey = "OrderDetails";
protected $fillable = array('OrderHeaderID, ProductID, QtyOrdered');
public function orderHeader(){
return $this->belongsTo('App\OrderHeader', 'OrderHeaderID', 'OrderID');
}
public function product(){
return $this->belongsTo('App\Product', 'ProductID', 'pID');
}
}
And:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class OrderHeader extends Model
{
//
protected $table = 'OrderHeader';
protected $primaryKey = 'OrderID';
protected $fillable = array('ShippingID');
public function orderDetails(){
return $this->hasMany('App\OrderDetail','OrderHeaderID','OrderID');
}
public function shippingAddress(){
return $this->belongsTo("App\Shipping", 'ShippingID', 'ShippingID');
}
public function user(){
return $this->belongsTo("App\User", 'UserID');
}
}
EDIT: Using dd($orderDetails) to see varible contents without attempting to set OrderHeaderID ejects the following:
OrderDetail {#172 ▼
#table: "OrderDetails"
#primaryKey: "OrderDetails"
#fillable: array:1 [▼
0 => "OrderHeaderID, ProductID, QtyOrdered"
]
#connection: null
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:2 [▼
"QtyOrdered" => "1"
"ProductID" => "7"
]
#original: []
#relations: array:1 [▼
"product" => Product {#187 ▼
#table: "Product"
#primaryKey: "pID"
#connection: null
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:8 [▼
"pID" => "7"
"pName" => "P1"
"pBrand" => "pbrand"
"pCurrentType" => "AC"
"pVoltage" => "4.5"
"pPrice" => "5.5"
"pStock" => "6"
"ImagePath" => null
]
#original: array:8 [▼
"pID" => "7"
"pName" => "P1"
"pBrand" => "pbrand"
"pCurrentType" => "AC"
"pVoltage" => "4.5"
"pPrice" => "5.5"
"pStock" => "6"
"ImagePath" => null
]
#relations: []
#hidden: []
#visible: []
#appends: []
#fillable: []
#guarded: array:1 [▼
0 => "*"
]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
]
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▼
0 => "*"
]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: false
+wasRecentlyCreated: false
}
Using dd($orderDetail) on $orderDetail->orderHeader()->associate(OrderHeader::find($order->OrderID));
OrderDetail {#172 ▼
#table: "OrderDetails"
#primaryKey: "OrderDetails"
#fillable: array:1 [▼
0 => "OrderHeaderID, ProductID, QtyOrdered"
]
#connection: null
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:3 [▼
"OrderHeaderID" => null
"QtyOrdered" => "11"
"ProductID" => "7"
]
#original: []
#relations: array:1 [▼
"product" => Product {#187 ▼
#table: "Product"
#primaryKey: "pID"
#connection: null
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:8 [▶]
#original: array:8 [▶]
#relations: []
#hidden: []
#visible: []
#appends: []
#fillable: []
#guarded: array:1 [▶]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
]
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▼
0 => "*"
]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: false
+wasRecentlyCreated: false
}
Using it on $orderDetail->OrderHeaderID = $order->OrderID;
OrderDetail {#172 ▼
#table: "OrderDetails"
#primaryKey: "OrderDetails"
#fillable: array:1 [▼
0 => "OrderHeaderID, ProductID, QtyOrdered"
]
#connection: null
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:6 [▼
"QtyOrdered" => "1"
"ProductID" => "7"
"OrderHeaderID" => null
"updated_at" => "2016-04-20 12:53:02.000"
"created_at" => "2016-04-20 12:53:02.000"
"OrderDetails" => 13
]
#original: array:6 [▼
"QtyOrdered" => "1"
"ProductID" => "7"
"OrderHeaderID" => null
"updated_at" => "2016-04-20 12:53:02.000"
"created_at" => "2016-04-20 12:53:02.000"
"OrderDetails" => 13
]
#relations: array:1 [▼
"product" => Product {#187 ▶}
]
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▼
0 => "*"
]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: true
}
Using it on $orderDetail->orderHeader()->associate($order);
OrderDetail {#172 ▼
#table: "OrderDetails"
#primaryKey: "OrderDetails"
#fillable: array:1 [▼
0 => "OrderHeaderID, ProductID, QtyOrdered"
]
#connection: null
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:6 [▼
"QtyOrdered" => "1"
"ProductID" => "7"
"OrderHeaderID" => null
"updated_at" => "2016-04-20 13:00:32.000"
"created_at" => "2016-04-20 13:00:32.000"
"OrderDetails" => 15
]
#original: array:6 [▼
"QtyOrdered" => "1"
"ProductID" => "7"
"OrderHeaderID" => null
"updated_at" => "2016-04-20 13:00:32.000"
"created_at" => "2016-04-20 13:00:32.000"
"OrderDetails" => 15
]
#relations: array:2 [▼
"product" => Product {#187 ▼
#table: "Product"
#primaryKey: "pID"
#connection: null
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:8 [▶]
#original: array:8 [▶]
#relations: []
#hidden: []
#visible: []
#appends: []
#fillable: []
#guarded: array:1 [▶]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
"orderHeader" => OrderHeader {#177 ▼
#table: "OrderHeader"
#primaryKey: "OrderID"
#fillable: array:1 [▼
0 => "ShippingID"
]
#connection: null
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:10 [▼
"OrderId" => "4"
"UserID" => "1"
"ShippingID" => null
"OrderCompleted" => "0"
"OrdersShipped" => "0"
"TotalPrice" => null
"created_at" => "2016-04-11 14:57:25.000"
"updated_at" => "2016-04-11 14:57:25.000"
"CreditCard" => null
"VerficationCode" => null
]
#original: array:10 [▼
"OrderId" => "4"
"UserID" => "1"
"ShippingID" => null
"OrderCompleted" => "0"
"OrdersShipped" => "0"
"TotalPrice" => null
"created_at" => "2016-04-11 14:57:25.000"
"updated_at" => "2016-04-11 14:57:25.000"
"CreditCard" => null
"VerficationCode" => null
]
#relations: []
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▼
0 => "*"
]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
]
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▶]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: true
}
Using it on '$order->orderDetails()->save($orderDetail);'
OrderDetail {#172 ▼
#table: "OrderDetails"
#primaryKey: "OrderDetails"
#fillable: array:1 [▼
0 => "OrderHeaderID, ProductID, QtyOrdered"
]
#connection: null
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:6 [▼
"QtyOrdered" => "1"
"ProductID" => "7"
"OrderHeaderID" => null
"updated_at" => "2016-04-20 13:17:18.000"
"created_at" => "2016-04-20 13:17:18.000"
"OrderDetails" => 16
]
#original: array:6 [▼
"QtyOrdered" => "1"
"ProductID" => "7"
"OrderHeaderID" => null
"updated_at" => "2016-04-20 13:17:18.000"
"created_at" => "2016-04-20 13:17:18.000"
"OrderDetails" => 16
]
#relations: array:1 [▼
"product" => Product {#187 ▶}
]
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▼
0 => "*"
]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: true
}
EDIT: Adding details on table structure in case it helps with debugging
CREATE TABLE [dbo].[OrderDetails] (
[OrderDetailID] INT IDENTITY (1, 1) NOT NULL,
[OrderHeaderID] INT NULL,
[ProductID] INT NULL,
[QtyOrdered] INT NULL,
[created_at] DATETIME NOT NULL,
[updated_at] DATETIME NOT NULL,
PRIMARY KEY CLUSTERED ([OrderDetailID] ASC),
CONSTRAINT [orderdetails_orderheaderid_foreign] FOREIGN KEY ([OrderHeaderID]) REFERENCES [dbo].[OrderHeader] ([OrderId]),
CONSTRAINT [orderdetails_productid_foreign] FOREIGN KEY ([ProductID]) REFERENCES [dbo].[Product] ([pID])
);
CREATE TABLE [dbo].[OrderHeader] (
[OrderId] INT IDENTITY (1, 1) NOT NULL,
[UserID] INT NOT NULL,
[ShippingID] INT NULL,
[OrderCompleted] BIT NOT NULL,
[OrdersShipped] BIT NOT NULL,
[TotalPrice] FLOAT (53) NULL,
[created_at] DATETIME NOT NULL,
[updated_at] DATETIME NOT NULL,
[CreditCard] NVARCHAR (50) NULL,
[VerficationCode] NCHAR (3) NULL,
PRIMARY KEY CLUSTERED ([OrderId] ASC),
CONSTRAINT [orderheader_userid_foreign] FOREIGN KEY ([UserID]) REFERENCES [dbo].[users] ([id]),
CONSTRAINT [fk_OrderShipping] FOREIGN KEY ([ShippingID]) REFERENCES [dbo].[Shipping] ([ShippingID])
);
Try this:
public function orderProduct(Request $request) {
//Try and find the current incomplete order. If find fails, then create new order.
var $order = null;
try{
$order = OrderHeader::where("UserID","=", Auth::user()->id)->where('OrderCompleted', '=', false)->firstOrFail();
}catch(\Illuminate\Database\Eloquent\ModelNotFoundException $e){
$order = new OrderHeader;
//associate user
$order->UserID = Auth::user()->id;
//mark order incomplete
$order->OrderCompleted = false;
$order->OrdersShipped = false;
$order->save();
}
//find matching or create new order detail. Update or add details and ade it to order.
/**
*Somewhere in here is the problem(s)
*The four or so lines I've commented out are all different attempts
*to get the value in the database.
*/
var $orderDetail = null;
$productID = $request->input("pID");
try{
$orderDetail = $order->orderDetails()->where("ProductID", "=", $productID)->firstOrFail();
//add feilds assignment
}catch(\Illuminate\Database\Eloquent\ModelNotFoundException $e){
$orderDetail = new OrderDetail;
$orderDetail->OrderHeaderID = $order->OrderID;
$orderDetail->QtyOrdered = $request->input("qty");
$orderDetail->ProductID = $productID;
$orderDetail->save();
//$order->orderDetails()->save($orderDetail);
//$orderDetail = OrderDetail::create(['OrderHeaderID' => $order->OrderId,'ProductID'=> $request->input("pID"), 'QtyOrdered' => $request->input("qty")]);
}
return $orderDetail;
//ProductController::cartView($order);
}

Categories