Update record using laravel - laravel

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.

Related

How to queue the logics in controller

I have used two logic in my controller in my laravel project
public function multiStore()
{
$user = User::create([
'name'=>$request->name,
'email'=>$request->email,
'password'=>Hash::make($request->name),
]);
$post = MyPost::create([
'name'=>$request->post_name,
'body'=>$request->post_body,
]);
return redirect()->to('/admin/home);
}
Is it possible to make like if user is created successfully only then the post will be created so that I can use post created by user relationship
I have tried something like if condition but it is not working
You can try the code bellow , I assume you have a user_id field in posts table since you mentio9ned a relation ship. This is not the best way but i try to keep things simple, so I just edited the code.
Note : make sure you listed all the table fields in protected $fillable in your model before using Create()
public function multiStore()
{
$user = User::create([
'name'=>$request->name,
'email'=>$request->email,
'password'=>Hash::make($request->name),
]);
if($user){
$post = MyPost::create([
'user_id' => $user->id
'name'=>$request->post_name,
'body'=>$request->post_body,
]);
}
return redirect()->to('/admin/home);
}
Enclose your query in database transaction
https://laravel.com/docs/5.8/database#database-transactions
Either you can:
DB::transaction(function() {
Model::create();
AnotherModel::create();
});
Or you can use the following to find and catch error...
DB::beginTransaction();
// Your queries here...
// Model::create();
// AnotherModel::create();
DB::commit();

why one table is updating and the other not in laravel?

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.

Query returning every row null in laravel

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

-Laravel 5.2 insert logged in users foreign key automatically into product table when creating product

i've been working on a CRUD system lately, what i want is that when a logged in user creates a product on my website his name will automatically be inserted as a foreign key into my product table.
this is my Product model i've made for it.
//inkoopprijs = sell price
//verkoop prijs = buy price
//naam = product name
protected $fillable = ['naam', 'inkoopprijs', 'verkoopprijs','users_id','created_at', 'updated_at'];
protected $table = "product";
this is my ProductController store function
public function store(Request $request)
{
$product = Product::create($request->only(['naam', 'inkoopprijs', 'verkoopprijs', 'users_id']));
return redirect(route('product.index'));
}
You can do this with Eloquent events like so:
Product::creating(function ($product) {
$user = auth()->user();
$product->users_id = $user->id;
});
You can access the current logged in user with Auth::user(); or auth()->user();
We can also access the identifier with Auth::id();
Product::create([
'naam' => $request->get('naam'),
'inkoopprijs' => $request->get('inkoopprijs'),
'verkoopprijs' => $request->get('verkoopprijs'),
'users_id' => \Auth::id()
]);
I hope this is what you meant.
You can use users id as hidden field in the form but need to consider the security aspects of using users id in the form. It depends on where you are using. May be you can use this method is the user is already authenticated.
<input type="hidden" name="users_id" value="{{Auth::user()->id}}">

Inserting a new relationship

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();

Resources