Laravel update pivot table - laravel

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]);
}

Related

Attempt to read property "id" on null - Laravel 8

I have problem with this error. I made relationship between :
Meals-Category (hasOne)
Meals-Ingredients (hasMany)
Meals-Tags (hasMany)
Everything is normal with seeding, but when I want to open on endpoint, this messege shows :
"Attempt to read property "id" on null"
Here is my code from Meals Resources, Model and Controller :
Resource:
class Meals extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'description' => $this->description,
'status' => $this->deleted_at > 0 ? 'deleted' : 'created',
'category' => [
'id' => $this->category->id,
'title' => $this->category->title,
'slug' => $this->category->slug,
],
'tags' => TagsResource::collection($this->tags),
'ingredients' => IngredientsResource::collection($this->ingredients),
];
}
}
Model:
class Meals extends Model
{
use SoftDeletes;
use HasFactory;
protected $fillable = ['title', 'description'];
protected $dates = ['deleted_at'];
public function category()
{
return $this->hasOne(Category::class, 'meals_id');
}
public function tags()
{
return $this->hasMany(Tag::class, 'meals_id', 'id');
}
public function ingredients()
{
return $this->hasMany(Ingredient::class, 'meals_id', 'id');
}
}
Controller:
public function index()
{
$meals = Meals::with('category', 'tags', 'ingredients')->get();
return MealsResource::collection($meals);
}
your error means that $this->category is null
assign the category attribute like this :
'category' => $this->load('category')

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);
}

GROUP BY the relationship data in laravel

I am fetching products along with its relationship. I have done this:
$data = $this->products->with('images')->with('colors')->where('slug', $slug)->first();
And in the Product model, I have written:
public function images(){
return $this->hasMany('App\Models\ProductImages', 'product_id');
}
public function colors(){
return $this->hasMany('App\Models\ProductSizes', 'color_id');
}
I am storing color_id in the product_sizes table so now when I do dd($data). It gives me 5 data inside the object where the size_id are different but the color_id are same. Is it possible to group the data coming in colors relationship?
I tried using array_unique in the blade but that did not gave me to use the following function:
public function colorInfo(){
return $this->belongsTo('App\Models\Color', 'color_id');
}
I want to group the color_id coming in the colors relationship to display available colors of the product.
Code as per request:
Product Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = ['name','slug','sku','category_id','brand_id','video','status', 'specification', 'description','warranty', 'vendor_id'];
public function getRules(){
$rules = [
'name' => 'bail|required|string|unique:products,name',
'slug' => 'bail|required|string|unique:products,slug',
'sku' => 'bail|required|string|unique:products,sku',
'specification' => 'bail|required|string',
'description' => 'bail|required|string',
'category_id' => 'required|exists:product_categories,id',
'brand_id' => 'nullable|exists:brands,id',
'vendor_id' => 'nullable|exists:vendors,id',
'video' => 'nullable|string',
'warranty' => 'nullable|string',
'status' => 'nullable|in:active,inactive',
];
if($rules != 'add'){
$rules['name'] = "required|string";
$rules['slug'] = "required|string";
$rules['sku'] = "required|string";
}
return $rules;
}
public function category(){
return $this->belongsTo('App\Models\ProductCategory');
}
public function brand(){
return $this->belongsTo('App\Models\Brand');
}
public function VendorName(){
return $this->belongsTo('App\Models\Vendor', 'vendor_id');
}
public function images(){
return $this->hasMany('App\Models\ProductImages', 'product_id');
}
public function sizes(){
return $this->hasMany('App\Models\ProductSize', 'product_id');
}
public function colors(){
return $this->hasMany('App\Models\ProductSize', 'product_id');
}
public function finalCategory(){
return $this->belongsTo('App\Models\SecondaryCategory', 'category_id');
}
}
PRoduct Sizes Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ProductSize extends Model
{
protected $fillable = ['product_id','size_id', 'selling_price', 'purchase_price', 'discount','stock', 'color_id', 'quantity','total_price'];
public function getRules(){
$rules = [
'product_id' => 'required|exists:products,id',
'size_id' => 'required|exists:sizes,id',
'color_id' => 'required|exists:colors,id',
'selling_price' => 'required|string',
'purchase_price' => 'required|string',
'quantity' => 'required|string',
'total_price' => 'required|string',
'discount' => 'nullable|string',
'stock' => 'required|string',
];
return $rules;
}
public function colorInfo(){
return $this->belongsTo('App\Models\Color', 'color_id');
}
}
Get the product first.
$data = $this->products->with(['images', 'colors'])->where('slug', $slug)->first();
To get the distinct colors for that product.
$unique_product_colors = $data->colors->unique('color_id');
unique('color_id') method can be applied on a collection instance to get a new collection in which all the items will have unique color_id
Try This
$data = $this->products->with('images')->with('colors')->where('slug', $slug)->groupBy('product_sizes.color_id')->first();

Error storing Topic Model into the database using Sentinel

I have a small forum, im trying to create topic and replies for the store method.
routes.php
Route::get('board/{id}/create', 'TopicsController#create');
Route::post('board/{id}/create', 'TopicsController#store');
TopicsController.php
public function store()
{
$this->request->user()->topics()->create([
'board_id' => $this->request->id,
'title' => $this->request->title,
'body' => $this->request->body
]);
return redirect(url('/board/' . $this->request->id));
}
I am receiving this error.
Call to a member function topics() on null
Also note, i am using Sentinel https://github.com/rydurham/Sentinel from this repo.
<?php namespace App\Models;
class User extends \Sentinel\Models\User
{
protected $fillable = ['email', 'first_name', 'last_name'];
protected $hidden = ['password'];
public function topics()
{
return $this->hasMany(Topic::class);
}
public function replies()
{
return $this->hasMany(Reply::class);
}
public function getGravatarAttribute()
{
$hash = md5(strtolower(trim($this->attributes['email'])));
return "https://www.gravatar.com/avatar/$hash";
}
}
Updated Model
public function store($id)
{
$user = Sentry::getUser($id);
$user->topics()->create([
'board_id' => $this->request->id,
'title' => $this->request->title,
'body' => $this->request->body
]);
return redirect(url('/board/' . $this->request->id));
}
It seems that your user object is null. Properly retrieve the user using the id
public function store($id)
{
$user = \App\Models\User::find(\Sentinel::getUser()->id);
$user->topics()->create([
'board_id' => $this->request->id,
'title' => $this->request->title,
'body' => $this->request->body
]);
return redirect(url('/board/' . $this->request->id));
}

Laravel lists with relationship for a dropdown

I have two tables:
course
id
name
season_id
teacher_id
dates_id
description
...
course_dates
id
course_id
weekday
start
stop
...
In the first table are the basic stuff for the course. In the second table i only store the dates of the course (i.e. weekday 1 for monday, start -> the time of beginning and stop -> for the ending). The course can have more than one date.
Now i want to create a list for a dropdown like so:
course name (day, from-to)
same course name (another day, from-to)
another course name (day, from-to)
The name for the day i get over a little helper function.
How can i manipulate the parameter for the lists method, with an accessor?
Thanks for help!
course model
<?php
class Course extends \Eloquent {
protected $guarded = ['id', 'created_at', 'updated_at'];
//Relationship Holidays
public function holidays()
{
return $this->hasMany('Holiday');
}
//Relationship Teacher
public function teacher()
{
return $this->belongsTo('Teacher');
}
//Relationship User
public function bookings()
{
return $this->hasMany('Booking');
}
//Relationship Dates
public function dates()
{
return $this->hasMany('Dates');
}
//Accessor for Dates
public function getWeekdayAttribute()
{
//???
}
//Validation Rules
public static $rules = [
'name' => 'required',
'teacher_id' => 'required',
'description' => 'required',
'room' => 'required',
'price' => array('required', 'regex:/^\d*(\,\d{2})?$/'),
'maxuser' => 'required|numeric',
'target' => 'required'
];
//Custom Attribute Names
public static $names = [
'name' => 'Kursname',
'teacher_id' => 'Kursleiter',
'description' => 'Beschreibung',
'room' => 'Raum/Ort',
'price' => 'Preis',
'maxuser' => 'Max. Anzahl Teilnehmer',
'target' => 'Zielgruppe'
];
//Change Price Format Get
public function getPriceAttribute($price)
{
return number_format($price, 2, ',', '');
}
//Change Price Format Set
public function setPriceAttribute($price)
{
$this->attributes['price'] = str_replace(',', '.', $price);
}
//Unserialize Target Get
public function getTargetAttribute($target)
{
return unserialize($target);
}
//Serialize Target Set
public function setTargetAttribute($target)
{
$this->attributes['target'] = serialize($target);
}
}
Dates model
<?php
class Dates extends \Eloquent {
protected $guarded = ['id', 'created_at', 'updated_at'];
protected $table = 'course_dates';
public function courses()
{
return $this->belongsTo('Course')->orderBy('name');
}
//Validation Rules
public static $rules = [
'weekday' => 'required',
'start' => 'required|date_format:H:i',
'stop' => 'required|date_format:H:i'
];
//Custom Attribute Names
public static $names = [
'weekday' => 'Wochentag',
'start' => 'Von',
'stop' => 'Bis'
];
}
Helper function
//Display Weekday
function showWeekday($id)
{
$weekday = array(
'1' => 'Montag',
'2' => 'Dienstag',
'3' => 'Mittwoch',
'4' => 'Donnerstag',
'5' => 'Freitag',
'6' => 'Samstag',
'0' => 'Sonntag'
);
return $weekday[$id];
}
If I understood you right something like this will do:
CourseDate model
public function getNameAndTimeAttribute(){
return $this->course->name . ' ' . $this->attributes['start'] . ' - ' . $this->attributes['stop'];
}
And then:
$dropdown = CourseDate::with('course')->get()->lists('nameAndTime', 'id');

Resources