Add data to a Laravel pivot table - laravel

I have a database with 3 tables : users, events and user_event.
I create my event. Once my event is created, I would like to add users.
How can I add him via a form to add users?
My pivot table contain :
event_id, user_id
Do I need to create a UserEventController?
My model relations :
public function users()
{
return $this->belongsToMany('User')->withPivot('user_event');
}
For create an event :
public function store(Request $request)
{
$this->validate($request, [
'course_name' => 'required|max:255',
'academic_year' => 'required|max:4|min:4',
'exam_session' => 'required',
'date_event' => 'required'
]);
$event = new Event();
$event->course_name = $request->course_name;
$event->academic_year = $request->academic_year;
$event->exam_session = $request->exam_session;
$event->date_event = $request->date_event;
$event->save();
}
Thanks for your help !

So you need to use the attach()method :
$event->users()->attach($userId);
more informations here : Laravel Eloquent - Attach vs Sync

Since the event is already created, you can just use the event object to add an existing user, create a new one, or maybe even sync a list of users.
//create a new user
$event->users()->create(['name' => 'user name', 'email' => 'user email']);
//attach existing user
$event->users()->attach($userId);
//sync multiple existing users passing array of user ids
$event->users()->sync([1,2,4]);
You can see details about all of those methods and a few more here: https://laravel.com/docs/5.7/eloquent-relationships#inserting-and-updating-related-models

Related

Is it possible to save multiple Foreign key in Laravel to be able to see many Items table in a Package Items table? in Quasar 1 Laravel 2

I'm trying to achieve some like an Ecommerce website where a Product has Many Categories.
I have this form named PackageItem table (let's compare it to PRODUCT) and when I click the Item it gets the Items name from the Item table (let's also compare it to CATEGORIES)
I have this q-select that accepts multiple items.
This is my return in Vue
createOptions: [],
my Methods for getting the Items from the backend and bind it to the q-select
allPackageItemsData() {
const bearerToken = localStorage.getItem("Bearer");
this.$axios
.get("http://localhost:8000/api/allPackageItems", {
headers: {
Authorization: `Bearer ${bearerToken}`,
},
})
.then((response) => {
this.allPackageItems = response.data;
this.createOptions = response.data.map(
(packageitem) =>
// "(Item) " +
packageitem.name
// + " & " +
// "(Item ID) " +
// packageitem.id
);
});
},
As you can see I'm mapping so that I can get the Item name and bind it to the q-select (See Package Item Form above.)
However, I need to display the names in the Frontend and upon selecting the Items name in the q-select I wanted to get the ID of it and save it to the database. In short I need to display the name as it is but upon selecting it I need to get the ID and pass it to the database
The reason for this is that I need to get the ID of the Items so that I can display it
I'm getting a controller like this one
$packageitems = DB::table('packageitems')
->select(
'items.name',
'packageitems.price',
)
->join('items', 'items.id', '=', 'packageitems.item_id')
->where('items.activeInactive', '=', 'Active')
->get();
I wanted to save a Package Item that has Many Items as many as I want and upon getting the Item names I wanted to create a price for it. Let's say it as a promo in a grocery you have 5 different chips and save the price for 2 dollar as a promo more like a LAZADA PACKAGE or SHOPEE PACKAGE.
I'm trying to achieve like this one.
This is my Create PackageItem Controller
$
user = Auth::user();
$item = Item::arrayPackageItemSelect();
$fields = $request->validate([
'user_id' => 'required',
'item_id' => 'required',
'price' => 'required|numeric'
]);
$package = PackageItem::create([
'user_id' => $user->id,
'item_id' => implode(',' , $fields['item_id']), // If i put implode it gives
//error
'price'=> $fields['price']
]);
return response()->json($package, 201);
I tried using implode as I seen it one of the tutorials however it is using one table only that in my case I'm doing this with a join from another table.
my package Item model.
my Item model.
so I created a function arrayPackageItemSelect that gets the Id of the Items but display it to the frontend by the name. I got this from this article https://www.artofcse.com/learning/product-view-insert-update-delete
However, I'm having a hard time figuring out this logic both the backend and frontend. I tried searching an I can't find anything I'm looking for. I wanted to make a CRUD out of this.
first create the package with the price and user_id
then
check the request if the request->item is an array
if true $items = collect($request->items); collect the request->item array
then
$items->each(function ($item) use ($package ) {
$package ->items()->create($item);
});
this 3 lines of code will do the logic in inserting the package items referenced to the package id
on the package model
protected $fillable = [user_id,price];
public function items() {hasMany(item::class)}
item model
public function package(){belognsTo(packageItem::class)}

Laravel 8.0 facing issue while trying to update a table with vue form, 'Attempt to read property \"item_id\" on null'

So, i have a table called Items table and another table called item_quantities, on item_quantities ive a column named item_id which is connected to items table id. All the fillable properties on both tables are all in one form on the frontend, and i take care of the form fields on the backend
Whenever i try to update the quantity on the form which is from item_quantities's table with a form, i'm facing serious issue updating the item_quantities. getting Attempt to read property "item_id" on null.
It all started when i noticed a duplicate entries on the item-quantities table, so i deleted all the datas on it..
Here's is the form screenshot
The vue form
and the backend logic
public function saveData(Request $request, $id) {
// dd($request->name);
$updateGroceries = Item::where('id', $request->id)->get()->first();
$updateGroceries->update([
'name' => $request->name,
'description' => $request->description,
'price' => $request->price,
]);
if($updateGroceries) {
$item_quantity = ItemQuantity::where('item_id', $updateGroceries->id) ?
ItemQuantity::where('item_id', $updateGroceries->id)->get()->first() :
new ItemQuantity;
if($item_quantity->item_id == null) {
$item_quantity->item_id = $updateGroceries->id;
}
$item_quantity->quantity = $request->quantity;
$item_quantity->save();
}
}
I'M SO SORRY IF MY ENGLISH WAS'NT CLEARED ENOUGH
Thanks in anticipation
You can simply use firstOrNew() method. This will first find the item, if not exist create e new instance.
$item_quantity = ItemQuantity::firstOrNew(['item_id' => $updateGroceries->id]);
$item_quantity->quantity = $request->quantity;
$item_quantity->save();
Note that the model returned by firstOrNew() has not yet been persisted to the database. You will need to manually call the save method to persist it.
Actually your errors workflow as that:
$item_quantity=null;
$item_quantity->item_id;
You can do that with optional global helper:
optional($item_quantity)->item_id ?: 'default value';

Returning a Modal with relationships after creating in Laravel

I have a modal for example User. The User has relationships to Country and Currency modal as well. I would like to return a JSON object of the User with their relationships. I can achieve that using the code below:
$user = User::create($request->all()); // request contains all the information to create the user
$userDetails = User::with('country', 'currency')->where('id', $user->id)->first();
return json_encode($userDetails);
It works. However, is there a better or more recommended way to achieve this? Thank you for your time.
I found out that creating a new Laravel Resource and using the following approach seems much cleaner:
// in UserResource.php:
public function toArray($request)
{
return [
'id' => $this->id,
'country' => $this->country, // relationship
'currency' => $this->currency // relationship
]
}
// In controller:
return new UserResource($user);
Thanks!

How to get hasMany relation in laravel?

Pls bear with me . I am working on api with laravel :
The Idea is that I have table called ( cards ) this table contain column called ( service_id ) .
this column has relation with table ( services ).
This is cards database structure in image :
image of database
All thing is good with add one service_id , but now I need to make table cards hasMany services
So How can I do it , and the database structure what will be?
this is my old code to add new card :
public function store(Request $request)
{
$validator = \Validator::make($request->all(), [
'user_id' => 'required|unique:cards|exists:users,id',
'service_id' => 'required',
'numPhone' => 'required',
'location' => 'required',
],[],[
'user_id' => '( User id )',
'service_id' => 'service id',
'numPhone' => 'Phone Number',
]);
if ($validator->fails()){
return $this->apiRespone(null,$validator->errors()->all(),'Some input required');
}
$card = Card::create($request->all());
return $this->apiRespone(new cardResource($card),'Add card Successfully',201);
}
I think you need to create pivot table "cards_services" that has column id, card_id, service_id column and used relationship Sync() method of laravel to store/update.
In cards modal
public function services(){
return $this->belongsToMany('App\Models\Service','cards_services', 'card_id', 'service_id');
}
For save it.
$cards->services()->sync([1,2]); //1 and 2 is service ID and $cards is card modal object
here you have service_id in your cards table
so i think it will be easier to implement service hasMany cards and cards belongsTo service
add this in your service model
public function cards(){return $this->hasMany('App\Cards');}
add this in your cards model
public function service(){return $this->belongsTo('App\Service');}
Note: please rewrite path and Model name according to your requirement

how to save multiple dropdownlist yii2

I'm trying to save multiple data from a dropdownlist, I have 2 tables Asistencia and Mecanico in the table Asistencia i have this in the _form
<?php
echo $form->field($model, 'mecanico_id[]')
->dropDownList(ArrayHelper::map(Mecanico::find()->all(), 'id_mecanico', 'nombre'),
[
'multiple'=>'multiple',
'class'=>'chosen-select input-md required',
]
)->label("Mecanicos");
?>
i know if i want to save multiple data i have to change in controllers-> actionCreate/Update but i dont know how. Here is my actionCreate
public function actionCreate()
{
$model = new Asistencia();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id_asistencia]);
}
return $this->render('create', [
'model' => $model,
]);
}
I need sample controller code explaining how to save multiple items from a drop down list to the database, as well as update the list of saved items. Thanks.
here is my table of Asistencia
Asistencia table
Table of Mecanico
Mecanico table
and the relation of those 2 table
enter image description here
For example you have Product and Category many to many relation.
In your Product model,
Declare field:
public $categories_ids;
Put it in 'safe' in rules():
[['categories_ids'], 'safe']
3.Declare AfterSave function:
public function afterSave($insert, $changedAttributes) {
// If this is not a new record, unlink all records related through relationship 'categories'
if(!$this->isNewRecord) {
// We unlink all related records from the 'categories' relationship.
$this->unlinkAll('categories', true);
// NOTE: because this is a many to many relationship, we send 'true' as second parameter
// so the records in the pivot table are deleted. However on a one to many relationship
// if we send true, this method will delete the records on the related table. Because of this,
// send false on one to many relationships if you don't want the related records deleted.
}
foreach($this->categories_ids as $category_id) {
// Find and link every model from the array of ids we got from the user.
$category = Category::findOne($category_id);
$this->link('categories', $category);
}
parent::afterSave($insert, $changedAttributes);
}
Decare AfterFind function():
public function afterFind(){
parent::afterFind();
$this->categories_ids = ArrayHelper::getColumn($this->categories, 'id');
}
Declare relation:
public function getCategories() {
return $this->hasMany(Category::className(), ['id' => 'category_id'])->viaTable('product_category', ['product_id' => 'id']);
}
I hope it will help to you.

Resources