What is use of attach() method in Laravel? - laravel

i dont have a idea what is use of this method i saw something on someone code like this.
$user = JWTAuth::parseToken()->authenticate();
$new_car = new Car();
$new_car->name = $request->name;
$new_car->age = $request->age;
$new_car->model = $request->model;
$new_car->save();
$time = new Reservation();
$time->from_date = $request->from_date;
$time->to_date = $request->to_date;
$time->from_time= $request->from_time;
$time->to_time = $request->to_time;
$time->save();
// Attach the reservation to the car's reservations
$new_car->Reservation()->attach($time->id);
// Attach the car to the user cars
$user->cars()->attach($new_car->id);
hopefully someone can explain me well.

Attaching / Detaching
Attach is used mainly Eloquent Relationship in Many To Many Relationships. It mainly uses intermediate table data insert or update. For example, let's imagine a user can have many roles and a role can have many users. You may use the attach method to attach a role to a user by inserting a record in the relationship's intermediate table:
For more details

Related

Laravel Many-To-Many relationship with multiple functions

I thought I was going quite well in developing my Laravel skills, but it seems I am stuck and can't find the solution online yet.
My project is set up in Laravel and Vue and I am trying to store a product with ingredients. The products are in the products table. The ingredients in the ingredients table. I succeeded in storing the product with a brand_id and later retrieve the brand (one-to-many), but I don't know how to do this for many-to-many: Ingredients to products.
Since I am working with Vue I have add JSON output that posts my data.
public function store()
{
$product = new Product();
$product->ean = request('ean');
$product->name = request('productName');
$product->brand_id = request('brandId');
$ingredients = request('ingredients');
$product->save();
}
As I explained above saving the product is going well.
But now I need to do something with the $ingredients array, I've found lines like these:
$user->roles()->save($role);
So I think I have to do a foreach loop for all ingredients and within do this:
$product->ingredients()->save($ingredient);
What I fail to understand. This array will contain existing ingredients that are already stored, but also new ingredients that have to be added to the ingredients table. How to make this work?
So store new ingredients in it's table and also store the relation in the eloquent table. I might be close, I might be far off, anyone?
While looping the ingredients, look into the firstOrNew() method:
foreach($request->input("ingredients") AS $ingredient){
$ingredient = Ingredient::firstOrNew(["name" => $ingredient]);
// Note: assumed name for column that matches `$ingredient` from array, adjust as needed.
}
While in that loop, attach() your $ingredient to your new $product. Your code should look like this when fully implemented:
$product = new Product();
...
$product->save();
foreach($request->input("ingredients") AS $ingredient){
$ingredient = Ingredient::firstOrNew(["name" => $ingredient]);
$product->ingredients()->attach($ingredient->id);
}
attach() will associate this new or existing $ingredient with the new $product by adding a record to the pivot between Product and Ingredient. The reason you can't use $product->ingredients()->save($ingredient); is that this is a many-to-many, which requires attach(). $model->relationship()->save(); is used for a one-to-many.
Full documentation on the creation methods can be found here: https://laravel.com/docs/5.8/eloquent#other-creation-methods

How to save record in database using belongs to many relation in laravel

I have three tables: restaurant_location, cuisine_restaurant_location and cuisines.
There is a list of all cuisines in my cuisines table. I have all the details of the restaurant in my restaurant_location table. A restaurant can have many cuisines so I made a table cuisine_restaurant_location in which there are two columns cuisine_id and restaurant_id. I have created a belongs to many relation in my restaurant_location model.
restaurant_location model
public function cuisines()
{
return $this->belongsToMany(Cuisine::class, 'cuisine_restaurant_location', 'restaurant_id', 'cuisine_id');
}
I have a form in which all the details of the restaurant along with cuisines is supposed to be added. Right now I am adding all the details of the restaurant. Now the question is how can I insert the cuisines in "cuisine_restaurant_location".
Controller
$rest = new restaurant_location;
$rest->name = $request->input('name');
$rest->description = $request->input('desc');
$rest->save();
$cuisine = new cuisine_restaurant_location
$cuisine_lists = $request->input('cuisines');
foreach ($cuisine_lists as $cuisine_list) {
$cuisine->name = $cuisine_list;
}
You can use the sync and attach methods, described in the Many to many section of the eloquent documentation, for that:
$rest->cuisines()->attach([$cuisineIds])
Where cuisineIds is the list of ids of the cuisines you want to relate.
The difference between sync and attach is that sync will remove all id's not present on the array of ids you are passing.
Try sync() method:
$h = [];
if (isset($input["cuisine_id"])) {
$h = $input["cuisine_id"];
}
$restaurant_location->cuisines()->sync($h);

Laravel avoid relationship query on laravel after object creation

How to avoid querying relationship after object creation?
$store = new Store();
$store->name = 'Store 1';
$store->save();
return response()->json($store->products());
Laravel is querying products table. I would like to avoid that since I know there is none. This is just an example.
return response()->json([]); is not an option. In real world I really need to use $store->products().
Use the wasRecentlyCreated property of model to identify if the model was inserted during the current request lifecycle.
$data = $store->wasRecentlyCreated ? [] : $store->products();

HasMany relationship attach model without saving directly

The following is just an example: Take the following two models with their relationships:
User => hasMany('Address', 'user_id')
Address => => belongsTo('User', 'user_id')
I want to be able to link an address with an user with out directly saving it.
something like:
$user = new User();
$user->name = "John";
$address1 = new Address();
$address1->street = "Foo street";
$address2 = new Address();
$address2->street = "Bar street";
$user->addresses()->push($address1);
$user->addresses()->push($address2);
//do some stuff to maybe validate some things or pass the user object to some other controllers that handels it
//Save the user and the addresses here.
$user->save()
So this different that $user->addresses()->saveMany([$address1, $address2]);
Hope you anyone give me an elegant solution.
You should distinguish your validation action from the save action. You can achieve this by creating different methods in the Object Controller. One for the validations that you will check for duplicates,similar etc and then if validation passes you should redirect to a store route where you 'll create and save the objects.

Create multiple objects from api post in laravel

Im at a bit of a loss. I have an api that will create a user upon a request. This is done no problem.
I also want to create another controller action or add to my current action the ability to create an address for the same user.
Is there an easy way to do this? Or should I stick to the
$user = new User(Input::all());
$user->save();
$address = new Address(Input::all());
$address->save();
You should set up relationships between your User and Address model - http://laravel.com/docs/eloquent#relationships and use associate/sync() to connect the dots.
This is a relationship problem. An address to a user will most likely be One-to-One (i.e., each Userhas a unique Address). A User might have an Address, but an Address must have a User. So in essence, the Address belongs to User.
Create two tables users and addresss, and add user_id to the address table as a column.
Then you define your relationships:
// In your User.php model
public function address()
{
return $this->hasOne('Address');
}
// In your Address.php model
public function user()
{
return $this->belongsTo('User');
}
Note when you use the correct notation, you can just define the model name, and not specify the pivot column. That is why I have defined the class addresss with an extra 's' to make it plural. I personally don't care about the spelling and rather Laravel take care of everything. Otherwise read the documentation on how to define the pivot column
Then you can use associate easily:
$user = new User();
// Fill $user however you want
$address = new Address();
// Fill $address however you want
$user->associate($address);
$user->save();
I was able to figure it out!
I wound up utilizing the Ardent package to help me validate my models before they hit the save method.
if my models didnt validate i will return all the errors to the user.
If they did validate my models would be created.
As for the association I am using the has many relation ship on the User and belongs to on the Address.
I used the following to save the address to the user
$address = $user->address()->save($address);
however I could only preform this after the initial user object was saved.
Thanks for all the responses guys they lead me in the right direction!

Resources