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.
Related
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
How can i get article owner user_id and save to notifiable_id field
Suppos
$articlecomment = $article_owner_id
My code:
$articlecomment = new Article_comment();
$articlecomment->user_id = Auth::user()->id;//Comment by user id
$articlecomment->article_id = $request->articleid;
$articlecomment->comment = $request->comment;
$articlecomment->save();
auth()->user()->notify(new ArticleNotification($articlecomment));
//$articlecomment->user()->notify(new ArticleNotification($articlecomment));
Database Screenshot
i want article_owner_user_id on notifible_id field
enter image description here
Solved
$articlecomment->save();
$article = Article::where('id','=',$request->articleid)->first();
if($article->user_id != Auth::User()->id){
$article->user->notify(new ArticleNotification($article));
}
This is database i need article_owner_id on notifible_id field click here to see screenshot
If you have a relationship set up for your Article_comment and Article models, you can access the "Article Owner" through the relation.
For example, define a relation for your "Article" model inside your Article_comment class (assuming Article is the name of your model):
class Article_comment extends Model {
....
public function article() {
return $this->hasOne('App\Article', 'id', 'article_id')
}
....
}
Once you have that set, you can access your relation (and subsequent properties) like so (assuming article_owner_id is a property of your Article model):
$articlecomment->article->article_owner_id
Edit:
Whichever user you call notify on will notify that user. So to notify the article owner, you will need to get the user of the article and call notify from that instance (rather than the auth user). If you set up a relation to the user on your Article class, you can simply call notify from that, or get the user from the article_owner_id and call notify.
Example:
$user = User::where('id', '=', $articlecomment->article->article_owner_id)->first();
$user->notify(new ArticleNotification($articlecomment));
With a relation set on your Article class, you could instead call notify like this:
$articlecomment->article->user->notify(new ArticleNotification($articlecomment));
For more info on Eloquent relationships, see https://laravel.com/docs/5.6/eloquent-relationships#introduction
I have a form where the user can edit, create or delete shipping methods.
The user sends the form and the data is updated.
I want to return the user's shipping methods after they are edited.
But I seem to get the old data back, instead of the updated data.
$user = \App\User::where('user_id', $user->id)->first();
$user->shipping_methods->each(function($method) {
$method->delete();
});
$methods = [];
foreach ($request->input('methods') as $method) {
$methods[] = new \App\ShippingMethod($method);
}
$user->shipping_methods()->saveMany($methods);
return response()->json($user->shipping_methods->toArray());
(at the moment the code just deletes the old shipping methods and replaces them with the new ones). I am using eloquent relations to get the shipping methods.
So when I do:
return response()->json($user->shipping_methods->toArray());
how come I don't get the new results, instead I get the results from before the update? Is it using the results from the first $user->shipping_methods at line 3? Should I "refresh" the query somehow?
You have to reload the relationship:
return response()->json($user->load('shipping_methods')->shipping_methods->toArray());
You can also simplify the whole line:
return $user->load('shipping_methods')->shipping_methods;
The saveMany method of \Illuminate\Database\Eloquent\Relations\HasMany return instace of \Illuminate\Database\Eloquent\Collection and you must manually set relations
$shipping_methods = $user->shipping_methods()->saveMany($methods);
$user->setRelation('shipping_methods', $shipping_methods);
return response()->json($user->shipping_methods->toArray());
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!
I am laravel newbie and I am trying to follow the documentation.So I have two models, 'User' model and a 'UserPhone' model. A user has many phones.
User model:
public function userPhone() {
return $this->hasMany('UserPhone');
}
UserPhone model:
public function user(){
return $this->belongsTo('User');
}
On my controller I am trying to "copy" the documentation:
$userPhone = User::find(1)->userPhone;
Well the result is an error:
Trying to get property of non-object
I know that I am missing something here , but I cannot find it.
I'm pretty sure that you don't have an user with id of 1.
$userPhone = User::find(1)->userPhone;
This should work, but, if it doesn't find the user the first part:
User::find(1)
I will return a NULL and NULL is not an object, then you get the error: Trying to get property of non-object.
My advice is, try to do this
var_dump( User::find(1) );
And you if you receive just a NULL, you found the problem.
Well the answer is that everything was ok!
I had accidentaly left
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
before the UserPhone Model Class declaration..It was such a newbie mistake.
If you want to fetch Users with their related phone numbers (userPhone) you can use Eager Loading.
//get all users (User) with their respective phonenumbers (userPhone)
$users = User::with('userPhone')->get()
//get User with id==1, with his related phonenumbers (userPhone of User(1))
$user_1 = User::with('userPhone')->where('id',1)->first()
and than you can do
if(!is_null($user))
$phones_of_user_1 = $user_1->userPhone();
else
$phones_of_user_1 = array();
That way, if a user of id==1 exists, you fetch his phone numbers. Else, you get an empty array and no exception/error (trying to get property on a non-object) thrown .
That relationship would automatically be loaded for you.
$user = User::find(1);
echo $user->userPhone->id;
This is assuming you have your database tables are setup correctly according to laravel's conventions and you actually have a User with an ID of 1.
1) You are missing a pair of () after userPhone
$userPhone = User::find(1)->userPhone();
2) You are not using the 'find' method properly. I think what you want to do is :
$userPhone = User::userPhone()->get();
or
$userPhone = User::find($phoneId); //where $phoneId is the id of the phone you are trying to find.
The 'find' method return only one object and will try to find it with it's id.