Laravel 7 : attach pivot to table with multiple values - laravel

I'm creating a pivot tables for 3 columns
my pivot table name is : category_post_pad
category_id| post_id | pad_id
-----------|----------|--------
1 | 1 | 3
1 | 4 | 1
2 | 2 | 1
Each post sent by the user includes a category and an pad
Post Model
public function categories()
{
return $this->belongsToMany(Category::class,'category_post_pad','post_id','category_id');
}
public function pads()
{
return $this->belongsToMany(Pad::class,'category_post_pad','post_id','pad_id');
}
category model:
public function posts()
{
return $this->belongsToMany(Post::class,'category_post_pad','category_id','post_id');
}
pad model:
public function posts()
{
return $this->belongsToMany(Post::class,'category_post_pad','pad_id','post_id');
}
PostsController
public function store(Request $request)
{
$data = $request->all();
$post = Post::create($data);
if ($post && $post instanceof Post) {
$category = $request->input('categories');
$pad = $request->input('pads');
$post->categories()->attach([$category],[$pad]);
return redirect()->back();
}
}
but show me this error
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: insert into category_post_pad (category_id, post_id, 0) values (3, 104, 2))
how to fixit?

Try using the following code as the store function in your PostsController:
$request->validate([
'title' => 'required',
'body' => 'required',
'category_post_pad.*.category_id' => 'required|array|integer',
'category_post_pad.*.post_id' => 'required|array|integer',
'category_post_pad.*.pad_id' => 'required|array|integer',
]);
$date = [
'title' => $request->input('title'),
'body' => $request->input('body'),
];
$post = Post::create($date);
if ($post){
if (count($request->input('category_id')) > 0){
$date2 = array();
foreach ( $request->input('category_id') as $key => $value ){
$postCategory = array(
'post_id' => $post->id,
'category_id' => (int)$request->category_id[$key],
'pad_id' => (int)$request->pad_id[$key],
);
array_push($date2, $postCategory);
}
$post->categories()->attach($date2);
return redirect()->back();
}
}
Then, inside of your Post model change your catagory relation:
public function categories()
{
return $this->belongsToMany(Category::class,'category_post_pad','post_id','category_id')->withPivot('pad_id');
}

Related

How to make a CRUD for a PackageItem table and get the Item via foreignKey in another table? in Laravel

This is my Item model. I have made a function arrayPackageItemSelect that gets the id and equivalent it to the item name.
class Item extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'name',
'price',
'itemdescription',
'activeInactive'
];
public function packageitems()
{
return $this->hasMany(PackageItem::class);
}
public static function arrayPackageItemSelect()
{
$arr = [];
$items = Item::all();
foreach($items as $item){
$arr[$item->id] = $item->name;
}
return $arr;
}
}
my PackageItem Model
class PackageItem extends Model
{
protected $fillable = [
'user_id',
'item_id',
'price'
];
protected $table='packageitems';
public static function itemModel()
{
return $this->belongsTo(Item::class);
}
}
my PackageItem Controller (CREATE) and getting the Item ID from another table (Foreign key) so I can put a category for it.
public function addPackageItem(Request $request)
{
$user = Auth::user();
$item = Item::arrayPackageItemSelect();
echo $item; // when I echo this I get Array to Conversion String in POSTMAN
$fields = $request->validate([
'user_id' => 'required',
'item_id' => 'required',
'price' => 'required|numeric'
]);
// // echo $items;
$package = PackageItem::create([
'user_id' => $user->id,
'item_id' => $item,
'price'=> $fields['price']
]);
return response($package, 201);
}
What I get when I echo the Items
The results I get from POSTMAN
My Schema
This is where my reference is https://www.artofcse.com/learning/product-view-insert-update-delete
Can anybody help me what is wrong?
In your controller (addPackageItem method):
$package = PackageItem::create([
'user_id' => $user->id,
'item_id' => $fields['item_id'],
'price'=> $fields['price']
]);
Also, i think there is an error in your PackageItem model. belongsTo should not be called in a static method :
public function itemModel()
{
return $this->belongsTo(Item::class);
}

How do I fill order id when creating orders and orderitems table with 1 form?

How do I fill order id when creating orders and orderitems table with 1 form ?
I make order management system by laravel.
When user submit form of order it will create orders and orderitems table where orderitems table has 1 column named order_id. I do not understand how I fill order_id in orderitems table.
This is my OrderController
public function store(Request $request)
{
$order = Order::create([
'user_id' => $request->input('user_id'),
]);
$orderitem = Orderitem::create([
'order_id' => $request->input('order_id'),
'product_id' => $request->input('product_id'),
'quantity' => $request->input('quantity'),
]);
return redirect()->route('orders.index');
}
public function store(Request $request)
{
$order = Order::create([
'user_id' => $request->input('user_id'),
]);
$orderitem = Orderitem::create([
'order_id' => $order->id,
'product_id' => $request->input('product_id'),
'quantity' => $request->input('quantity'),
]);
return redirect()->route('orders.index');
}
First of all create a relationships in both model. In the Order model create a hasMany relation:
public function orderItems()
{
return $this->hasMany(OrderItem::class, 'order_id');
}
Then in OrderItem model create a reverse relation:
public function order()
{
return $this->belongsTo(Order::class, 'order_id', 'id');
}
Then finally in the controller
$order = Order::create([
'user_id' => $request->input('user_id'),
]);
$orderItems = $order->orderItems()->create([
'product_id' => $request->input('product_id'),
'quantity' => $request->input('quantity')
]);

Column not found:

public function AddWishlist($id)
{
$userid = Auth::id();
$check = DB::table('whishlists')
->where('user_id', $userid)
->where('whishlists', $id)
->first();
$data = ['user_id' => $userid, 'product_id' => $id];
if (Auth::check())
{
if ($check)
{
$notification = ['messege' => 'already added whisahlist', 'alert-type' => 'error'];
return redirect()->back()->with($notification);
}
else
{
DB::table('whishlists')->insert($data);
$notification = [
'messege' => 'Suucessafully added whisahlist',
'alert-type' => 'success'
];
return redirect()->back()->with($notification);
}
}
else
{
$notification = array(
'messege' => 'At first login your account',
'alert-type' => 'error'
);
return redirect()->back()->with($notification);
}
}
Problem
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'whishlists' in 'where clause' (SQL: select * from `whishlists` where `user_id` = 1 and `whishlists` = 37 limit 1)
the logic will be to change
->where('whishlists', $id)
with
->where('whishlist_id', $id)
if its not working, Please show us the table whishlists
Note:
if $id is the id of the wishlist, i think this line should be reviewed :
$data = ['user_id' => $userid, 'product_id' => $id];
because it set 'product_id' with the whishlist id

How to handle nested relation in laravel resource - 2

So I've been trying to get a second level relation out of my "CategoryResource" but it's not working, here is some of my code :
First, My model :
public function children()
{
return $this->hasMany(Category::class, 'parent_id', 'id');
}
public function sub_children()
{
return $this->hasMany(Category::class, 'parent_id');
}
and then the "CategoryResource" :
$data = [
'id' => $this->id,
'parent_id' => $this->parent_id,
'order' => $this->order,
'name' => $this->name,
'slug' => $this->slug,
'childs' => CategoryResource::collection($this->whenLoaded('children') && $this->whenLoaded('children')),
'created_at' => (string) $this->created_at,
'updated_at' => (string) $this->updated_at,
];
My Controller
return CategoryResource::collection(Category::where('parent_id',null)->with('children.sub_children')->get());
Is there anyway i can retrieve my nested relation through laravel resource ?
You could use with function in the relationship. It would be something like this:
public function children()
{
return $this->hasMany(Category::class, 'parent_id', 'id')
->with('children');
}
It is going to load the children and then "subChildren" as relations of the first object.
So, you are going to load it as:
$children = $originalObject->children;
foreach ($children as $c) {
$subChildren = $c->children;
}
Check if this works for your problem.

Laravel update pivot table

In laravel I'm trying to update a row from a pivot table. I have this relationships:
Invoice.php
class Invoice extends Model
{
public function items() {
return $this->belongsToMany('App\Item', 'invoice_items', 'invoice_id', 'item_id')->withPivot('quantity');
}
Item.php
class Item extends Model
{
public function invoices() {
return $this->belongsToMany('App\Invoice' ,'invoice_items', 'item_id', 'invoice_id')->orderBy('created_at', 'desc')->withPivot('quantity');
}
}
InvoiceItem.php
class InvoiceItem extends Pivot
{
protected $fillable = [
'quantity',
];
public function __construct(Model $parent, array $attributes,
$table, $exists = false)
{
parent::__construct($parent, $attributes, $table, $exists);
}
}
and in InvoicesController.php I have method update:
public function update(Request $request, $id)
{
$invoice = Invoice::findOrFail($id);
$invoice->update([
'number' => $request->number,
'status' => $request->status,
'place_issue' => $request->place_issue,
'date_issue' => $request->date_issue,
'date_payment' => $request->date_payment,
'description' => $request->description,
'company_id' => $request->company_id,
'user_id' => $request->user_id,
]);
Invoice::find($id)->items()->updateExistingPivot($request->quantity, ['quantity' => $request->quantity]);
return redirect('listInvoice');
}
Every time I try to update the field "quantity" is the old value. What am I doing wrong?
As each invoice may have multiple items, you can loop through and update the quantity of the item by its key.
I'm not sure what $request->quantity is returning. You may need some additional logic to ensure you are updating the correct item.
$items = $invoice->items->pluck('name', 'id')->toArray();
foreach ($items as $key => $item) {
$invoice->items()->updateExistingPivot($key, ['quantity' => $request->quantity]);
}

Resources