How to get hasMany relation in laravel? - 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

Related

How to scope results with pivot table October Cms

The solution to this is probably easy and I'm just missing it, but I can't seem to figure out how to limit "customers" based on the "user" that the customer belongs to.
This is a many to many relationship, so a customer can belong to more than one user and a user can have more than one customer.
Here is my relationship definition:
public $belongsToMany = [
'user_id' => [
'RainLab\User\Models\User',
'table' => 'tablename_users_customers',
]
];
And here is the scope function that doesn't work as I'd expect:
public function scopeUser($query) {
$user = Auth::getUser()->id;
return $query->where('user_id', $user)->get();
}
Finally, here is my error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'where clause' (SQL: select * from `tblcustomers` where `user_id` = 1)
Obviously, the error is because the "user_id" column doesn't exist in the 'tblcustomers' table, but rather in the pivot table. How can I use the "user_id" from the pivot table in my scope function? I need to only display Customers that belong to the currently logged in user.
Yes this can be possible
But First thing is you need to remove get() method from the scope, scope meant to return query object for chaining methods further.
Your relation and scope should look like this
// relation
public $belongsToMany = [
// PLEASE MAKE RELATION NAME CORRECT HERE
'users' => [ // not user_id, use `users`
'RainLab\User\Models\User',
'table' => 'tablename_users_customers',
// 'key' => 'customer_id', if needed
// 'otherKey' => 'user_id' if needed
]
];
// scope
use RainLab\User\Models\User;
public function scopeUser($query) {
return $query->whereHas('users', function($usersQuery) {
$user_id = Auth::getUser()->id;
return $usersQuery->where((new User)->getTable() . '.id', $user_id);
});
}
// usage
$result = Customer::user()->get();
dd($result);
// you will get only customers which has relation with current logged in user.
if any doubts please comment.

how to store data addtional column in pivot tavle laravel

i have pivot table like this
this is my Users model
public function getHousing()
{
return $this->belongsToMany(Housing::class, 'user_housing', 'user_id', 'housing_id')->withPivot('primary');
}
this is my Housing model
public function getUser()
{
return $this->belongsToMany(Users::class, 'user_housing', 'housing_id', 'user_id')->withPivot('primary');
}
i want to save primary with 1, this is my controller
$getData = $this->crud->show($id);
if (!$getData) {
return redirect()->route('admin.' . $this->route . '.index');
}
$data = $this->validate($this->request, [
'housing_group_id' => 'required',
'housing_id' => 'required',
'primary' => 'required',
]);
$getData->housing_id = $getData->getHousing()->pluck('id')->toArray();
$getData->getHousing()->sync($this->request->get('housing_id'), ['primary' => 1]);
$id = $getData->id;
i already add array fill primary 1, but i have error like this
SQLSTATE[HY000]: General error: 1364 Field 'primary' doesn't have a default value
how to save additional field in pivot table laravel ?
thanks
in sync with additional column in pivot table, you should pass an associative array for each id with column name as key and field value as value
$elements_array[$this->request->get('housing_id')]=['primary' => 1]
$getData->getHousing()->sync(elements_array);
if you have more than an 'id' to sync ... you must repeat the first step for each id.
check this:
https://stackoverflow.com/a/27230803/10573560

Laravel - Table with two columns, each has ID from different tables

I need to create a single objective that has a multi-select drop down wherein different departments can share that same objective. I wanted to create a relationship table with an output like this.
Department Table
id | name
1 Science Department
2 Math Department
3 Biology Department
Objective Table
id | name
1 Be the best
Relationship Table
objective_id | department_id
1 1
1 2
1 3
This is what I think of inside the controller.
public function store(Request $request) {
$objective = Objective::updateOrCreate(
[ 'id' => $request->id ?? null ],
[ 'name' => $request->name ]
);
// From multiple select drop down
foreach($request->departments as $department) {
RelationshipTable::updateOrCreate(
[ // what should be the case? ],
[
'objective_id' => $objective->id,
'department_id' => $department['id'],
]
);
}
}
I'm not sure on how I would define this in the Model and how I could call their relationship inside the resource. I even think that my controller is wrong or are there better ways to achieve this?
First You are running query under loop is a very bad process.. may this process will help u? change it as your need!
public function store(Request $request) {
$objective = Objective::updateOrCreate(
[
'id' => $request->id ?? null,
'name' => $request->name
]
);
// From multiple select drop down
$insert_array = [];
foreach($request->departments as $department) {
array_push($insert_array,[
'objective_id' => $objective->id,
'department_id' => $department['id'],
]);
}
RelationshipTable::updateOrCreate($insert_array);
}
//Relationship Should Be Like in this example
Relationship Model
public function object() {
return $this->hasOne('Model Class of Object' , 'objective_id ' , 'id')
}
public function depertment() {
return $this->hasMany('Model Class of depertment' , 'department_id' , 'id')
}

Add data to a Laravel pivot table

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

Update many multiple data with tables hasmany and belongsTo?

sorry for my english
I want two tables
Invoices
id
user_id
name
created_at
update_at
Invoicesitems
id
invoice_id
title
createad_at
update_at
Models
class Invoices extends eloquent{
public function invoicesitems(){
return $this->hasMany('Invoicesitem');
}
}
class Invoicesitems extends eloquent{
public function invoices(){
return $this->belongsTo('Invoice');
}
}
Now, for update the items of my invoices?
Example my invoices have 5 item, i need update to 10 items
first delete all items of my invoices and insert new ???
$invoices = Invoices::findOrFail($id);
$dataupdate = array(
'user_id' => Input::get('user'),
'name' => Input::get('name'),
);
$invoices->fill($dataupdate);
$invoices->save();
//Ok update invoices, now how to update items?
Thanks you.
If your business logic allows - you can just replace the invoice items.
$invoice = Invoices::findOrFail($id);
$dataupdate = array(
'user_id' => Input::get('user'),
'name' => Input::get('name'),
);
$invoice->update($dataupdate);
// replace invoice items
$invoice->invoicesitems()->delete();
$invoice->invoicesitems()->create($invoiceItems);
Note! This is quite straight solution. You can improve by using insert() method instead of create() for batch insert.

Resources