The user_enabled_notifications table has 2 rows of data. i wanted to fetch all the values in the id column.
$notificationData = UserEnabledNotifications::all();
dump($notificationData['id']); shows Undefined index: id
dump($notificationData->id); shows Property [id] does not exist on this collection instance
dump($notificationData[0]['id']); shows only 1 id. What else shall i try to fetch all the id column values in a single stretch.
However, dump($notificationData); shows the complete data in table as given below.
Illuminate\Database\Eloquent\Collection {#337
#items: array:4 [
0 => App\Models\UserEnabledNotifications {#338
#table: "user_enabled_notifications"
#fillable: array:3 [
0 => "userId"
1 => "notificationTypesId"
2 => "status"
]
#connection: "pgsql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:7 [
"id" => 1
"userId" => 1
"notificationTypesId" => 1
"status" => true
"deleted_at" => null
"created_at" => null
"updated_at" => null
]
#original: array:7 [
"id" => 1
"userId" => 1
"notificationTypesId" => 1
"status" => true
"deleted_at" => null
"created_at" => null
"updated_at" => null
]
#changes: []
#casts: array:1 [
"deleted_at" => "datetime"
]
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [
0 => "*"
]
#forceDeleting: false
#enableLoggingModelsEvents: true
#oldAttributes: []
}
1 => App\Models\UserEnabledNotifications {#339
#table: "user_enabled_notifications"
#fillable: array:3 [
0 => "userId"
1 => "notificationTypesId"
2 => "status"
]
#connection: "pgsql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:7 [
"id" => 2
"userId" => 1
"notificationTypesId" => 2
"status" => true
"deleted_at" => null
"created_at" => null
"updated_at" => null
]
#original: array:7 [
"id" => 2
"userId" => 1
"notificationTypesId" => 2
"status" => true
"deleted_at" => null
"created_at" => null
"updated_at" => null
]
#changes: []
#casts: array:1 [
"deleted_at" => "datetime"
]
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [
0 => "*"
]
#forceDeleting: false
#enableLoggingModelsEvents: true
#oldAttributes: []
}
The $notificationData is an object of type Illuminate\Database\Eloquent\Collection, a collection. If you want to get the id of individual elements. Pls do the followings:
foreach ($notificationData as $notification) {
dump($notification->id);
}
// Or
$notificationData->pluck('id')->toArray();
Try this
// get your main collection with all the attributes...
$notificationData = UserEnabledNotifications::get();
// build your second collection with a subset of attributes. this new
// collection will be a collection of plain arrays, not UserEnabledNotifications models.
$subset = $notificationData->map(function ($notification) {
return collect($notification->toArray())
->only(['id'])
->all();
});
dd($subset);
OR
$notificationData = $notificationData->pluck('id')->toArray();
dd($notificationData);
all() gives you an collection (similar to array), so it has index (0 and positive integers) for keys
use pluck() to get all specific value for a key
$notificationData = UserEnabledNotifications::pluck('id');
print($notificationData) // [1, 2, 3, 4, 5, 6, ...]
Related
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);
I'm trying to get a single value from Query Builder in Laravel but the problem is I'm getting an array.
this is my query result in Postman with dd($myVar):
[{"is_liked":1}]
and also with echo($myVar):
Collection {#976
#items: array:1 [
0 => NewsCommentLike {#970
#fillable: array:3 [
0 => "user_id"
1 => "news_comment_id"
2 => "is_liked"
]
#connection: "mysql"
#table: "news_comment_likes"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:1 [
"is_liked" => 1
]
#original: array:1 [
"is_liked" => 1
]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [
0 => "*"
]
}
]
}
and my code is:
$previous_is_liked = NewsCommentLike::query()->where(['user_id' => $user_id, 'news_comment_id' => $newsComment->id])->get(['is_liked']);
How to get a single value from is_liked not an array?
This is why you have ->value('my_column') method. So you'll end up with:
NewsCommentLike::query()
->where(['user_id' => $user_id, 'news_comment_id' => $newsComment->id])
->value('is_liked');
The advantage is that the value is retrieved directly from the database. If you call first() before it, it can be null thus break your code.
$previous_is_liked = NewsCommentLike::query()->where(['user_id' => $user_id, 'news_comment_id' => $newsComment->id])->first()->is_liked;
Calling first returns 1 result instead of an array, then you can call the column you want.
I believe you could also call it like this:
$previous_is_liked = NewsCommentLike::query()->where(['user_id' => $user_id, 'news_comment_id' => $newsComment->id])->first()->value('is_liked')
I'm developing a CMS, which uses yaml files to manipulate the theme. My problem is that I need to list the Submenus of a Menu. I access for example the Header menu where I can change the contents of it, but in that Header has submenus, I just want to list them.
I have a service that does a search
Since the data is an array, how do I print it on the screen?
public function query() {
/* #var $request Request */
$request = app('request');
/* #var $website Site */
$website = $request->route('website');
$menu = $request->route('submenu');
// Carega configurações do site
$this->service->loadWebsite($website->slug);
/*
- title: menu1
submenu:
- title: submenu 1.1
- title: submenu 1.2
- title: menu2
submenu:
- title: submenu 2.1
*/
/*
- title: menu1
- title: - submenu 1.1
- title: - submenu 1.2
- title: menu2
- title: - submenu 2.1
*/
// puxa os menus da configuração do site
$menus = $this->service->getWebsiteConfig($website->slug, 'menu.' . $menu . '.menu');
dd($menus);
return $menus;
}
SERVICE
protected function toWebisteMenuItemCollection(string $menu, array $rows) {
return collect($rows)->map(function (array $data, string $key) use ($menu) {
$data['id'] = $menu . '.' . $key;
if(isset($data['submenu']) && is_array($data['submenu'])) {
$data['submenu'] = $this->toWebisteMenuItemCollection($data['id'], $data['submenu']);
}
return new WebsiteMenuItem($data);
});
}
dd($menu)
#attributes: array:3 [
"title" => "Consórcio"
"submenu" => Collection {#647
#items: array:3 [
0 => WebsiteMenuItem {#642
#keyType: "string"
#fillable: array:7 [
0 => "id"
1 => "title"
2 => "label"
3 => "imagem"
4 => "website_image"
5 => "icons"
6 => "submenu"
]
#connection: null
#table: null
#primaryKey: "id"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#attributes: array:2 [
"title" => "Planos de Consórcio"
"id" => "header_submenu_menu.2.0"
]
#original: []
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [
0 => "*"
]
}
1 => WebsiteMenuItem {#645
#keyType: "string"
#fillable: array:7 [
0 => "id"
1 => "title"
2 => "label"
3 => "imagem"
4 => "website_image"
5 => "icons"
6 => "submenu"
]
#connection: null
#table: null
#primaryKey: "id"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#attributes: array:2 [
"title" => "Portal do Consorciado"
"id" => "header_submenu_menu.2.1"
]
#original: []
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [
0 => "*"
]
}
2 => WebsiteMenuItem {#646
#keyType: "string"
#fillable: array:7 [
0 => "id"
1 => "title"
2 => "label"
3 => "imagem"
4 => "website_image"
5 => "icons"
6 => "submenu"
]
#connection: null
#table: null
#primaryKey: "id"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#attributes: array:2 [
"title" => "Como Funciona o Consórcio"
"id" => "header_submenu_menu.2.2"
]
#original: []
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [
0 => "*"
]
}
]
}
var_dump($array_youd_like_to_print) will give you all the contents (even nested) of an array.
You can either use this as is, if it solves your problem, or use it to find where the value is that you are looking for (and how to access it in the array) and print that.
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';
}
}
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);
}