I'm just looking through the docs:
$post = Post::find(1);
$comments = array(
new Comment(array('message' => 'A new comment.')),
new Comment(array('message' => 'A second comment.')),
);
$post->comments()->save($comments);
I've implemented something similar to the above on my site, my question is, I wish to also insert a new Post at the same time, is there a way to do this, instead of using find?
Also what happens if the insert of the post fails, can I prevent the comments from being inserted?
Parent of the relationship must be saved prior to saving related models. Can't be done in 1 go. (btw push won't work for it either, in case you wonder).
$post = Post::create([ ... post data here ...]);
// or
$post = new Post;
$post->whatever = 'someValue';
$post->save();
// then
$post->comments()->saveMany($comments);
You can probably do it this way:
$post = new Post();
$post->title = 'my title';
$post->save();
$comments = array(
new Comment(array('message' => 'A new comment.')),
new Comment(array('message' => 'A second comment.')),
);
$post->comments()->saveMany($comments);
this way you will create new post and save comments for it. I haven't tested what happens if something goes wrong but I assume comments won't be inserted because there won't be related post id.
Why not first create a post then attach the related model something like this.
$post = new Post();
$post->save();
Then iterate through comments and assign the post_id attribute in comment table.
The id field of post model will be available if the post exists.
$comment = new Comment();
$comment->post_id = $post->id;
$comment->save();
Related
I have a question,
I have a form (view) and after submit it saves to the db.
one of the records is id.
when I open the form again for that ID and will press submit again
what will happened it will update the record? or try to create a new record and fail since id is primary key?
so it depends on your controllers etc if you have a updateController with the correct code it can be updated but you would also need a edit method as well, If you could share your code it will be easier to say what would happen instead of guessing
public function store(Request $request)
{
$this->validate($request,[
'name' => 'required|unique:categories',
]);
$category = new Category();
$category->name = $request->name;
$category->slug = str_slug($request->name);
$category->save();
Toastr::success('Category Successfully Save','Success');
return redirect()->route('admin.category.index');
}
If you're trying to update record based on it's id then you could do this
public function update($request)
{
$user = User::firstOrNew([
'id' => $request->id
]);
$user->first_name = $request->first_name;
$user->last_name = $request->last_name;
$user->save();
}
It will find a record with that id, if none was found then create a new record with that id. This is just for example but you need to validate every request before update/insert.
When I click the edit button, I am trying to bring data from two tables and them update them together. One is user table and other on is user detail table.
when I update the information, user table is getting updated but user_detail table is not getting updated rather creating a new row. how to solve that?
The same code is working for one table while it is not working for the other.
This is my update function.
public function update(Request $request, $id)
{
// $this->validate($request,[
// 'title'=>'required',
// 'body'=>'required',
// ]);
//$user=new User;
$user = User::find($id);
$user->student_no=$request->input('student_no');
$user->email=$request->input('email');
$user->save();
$user_detail=new Profile;
$user_detail = Profile::find($id);
$user_detail->student_no=$request->input('student_no');
$user_detail->profile_pic=$request->input('CID');
$user_detail->CID=$request->input('CID');
$user_detail->DOB=$request->input('DOB');
$user_detail->mobile_no=$request->input('mobile_no');
$user_detail->joining_year=$request->input('joining_year');
$user_detail->graduation_year=$request->input('graduation_year');
$user_detail->program_id=$request->input('programe_id');
$user_detail->work_experience=$request->input('work_experience');
$user_detail->save();
return redirect('/dashboard')->with('success','Post Updated');
The user table is getting updated but user_detail is not.
remove line,
$user_detail=new Profile;
and in line,
$user_detail = Profile::find($id);
here you can't do like this. You have to do something like this
$user_detail = Profile::where('user_id','=',$id)->first();
then your code should look like this,
public function update(Request $request, $id)
{
// $this->validate($request,[
// 'title'=>'required',
// 'body'=>'required',
// ]);
//$user=new User;
$user = User::find($id);
$user->student_no=$request->input('student_no');
$user->email=$request->input('email');
$user->save();
$user_detail = Profile::where('user_id','=',$id)->first();
$user_detail->student_no=$request->input('student_no');
$user_detail->profile_pic=$request->input('CID');
$user_detail->CID=$request->input('CID');
$user_detail->DOB=$request->input('DOB');
$user_detail->mobile_no=$request->input('mobile_no');
$user_detail->joining_year=$request->input('joining_year');
$user_detail->graduation_year=$request->input('graduation_year');
$user_detail->program_id=$request->input('programe_id');
$user_detail->work_experience=$request->input('work_experience');
$user_detail->save();
return redirect('/dashboard')->with('success','Post Updated');
Delete $user_detail=new Profile;
Use relations for update user details.
Read about $request->all() and Mass Assignment in Laravel.
Make form validation in separate files.
$user_detail = Profile::find($id);
in this line you are checking the profile data with the primary key of the profile table which might does not exist
You can try with
$user_detail = Profile::where('user_id',$id)->first();
user_id is the fk on profiles table from user id.
You should remove line $user_detail=new Profile;
and update line $user_detail = Profile::find($id); as following
$user_detail = Profile::where('user_id',$id)->first()
there two three things with your query.
$user_detail=new Profile;
$user_detail = Profile::find($id);
first of all no need for new profile line . It just made new object but you don't need that sine your going to update someone profile,
Now print your second line response weather your getting any response from it and also is it correct one because your finding id not user_id .
otherwise there is no problem with that.
hope you will find solution in this.
I'm trying to build a chat application using laravel echo and pusher, everything works but the data that returns to the databse is either null or the default value, here's the code
public function sendMessage(Request $request){
$conID = $request->conID;
$message1 = $request->message;
$user = Auth::user();
$fetch_userTo = DB::table('messages')
->where('conversation_id', $conID)
->where('user_to', '!=', Auth::user()->id)
->get();
$userTo = $fetch_userTo[0]->user_to;
$message = Message::create([
'user_from' => Auth::user()->id,
'user_to' => $userTo,
'conversation_id' => $conID,
'message' => $message1,
]);
if($message) {
$userMsg = DB::table('messages')
->join('users', 'users.id','messages.user_from')
->where('messages.conversation_id', $conID)->get();
broadcast(new MessagePosted($message))->toOthers();
return $userMsg;
}
}
NB: when i put insert() instead of create in the query the data goes through the database normally but there's an error in broadcasting
Have you tried to create a message like this? instead of using a model event?
$message = new Message;
$message->user_from = Auth::user()->id;
$message->$user_to = $userTo;
$message->conversation_id = $conID;
$message->message = $message1;
$message->save();
You have a lot more control this way, i.e
if($message->save()) { ... }
Or you could wrap the whole thing in a transaction?
Be sure your Message model allows the fields that you want to add in the $fillable array
Create method check fillable attributes into Laravel model. You have to write your all columns into fillable and then use create method.
Second solution is use Active Record technique. #Devin Greay answer is helpful to use Active record.
More information visit https://laravel.com/docs/5.6/eloquent#mass-assignment
$comment = Comment::create(['title' => 'test']);
will this work with model that is morphable?
It has these columns:
$table->string('commentable_type');
$table->biginteger('commentable_id')->unsigned()->index();
it doesn't seem that they will be filled if I use create here or will they?
right now I am doing it like this:
$comment = new Comment();
$comment->title = $title;
$comment->body = $body;
$this->comments()->save($comment);
but would like to swtich to create so I can mass assign instead of one by one.
$this->comments()->create($array);
Is definitely available for morphable models.
From Taylor Otwell himself: https://github.com/laravel/framework/issues/322
I've got three tables: blogs, posts, blog_post. Here is my code.
$post = new Post();
$post->title = HTML::entities(Input::get('title'));
$post->content = Input::get('content');
$post->status = isset($_POST['save']) ? 2 : 1;
$post->save();
$blog = Blog::where('user_id', '=', Auth::user()->id)->first();
$post = $blog->posts()->insert($post);
And I get:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
'47' for key 'PRIMARY'
I have one to many relation ships. A post can belong to many blogs.
at13 answer is correct. You are saving the post and then trying to insert it again through blog relationship.
According to your comments you should have:
$post->has_many_and_belongs_to('blog');
$blog->has_many_and_belongs_to('post');
With that in mind, to create many to many relationships, you should use attach().
For instance:
$post = new Post;
$post->title = "Foo Bar";
// ...
$post->save();
$user = Auth::user();
$blog = $user->blogs()->first();
$blog->posts()->attach($post);
Obs: I don't quite understand the concept of a post belonging to more than one blog.