This question already has an answer here:
Laravel adding data to pivot table while inserting new record
(1 answer)
Closed 1 year ago.
I have 3 tables
User(id,name,email)
Role(id,rolename)
role_user(user_id,role_id)
In roles table i have following data;
id rolename
1 admin
2 user
In this scenario, I have users table is associated to roles table with many to many relation.
I have one eloquent model as
UserModel
user_roles(){
belongsToMany('Role')
}
Now I want to save data in role_user table when i create user. I have roles in dropdown.
I am using following query
$user = new User();
$user->username = $data->username;
$user->email= $data->email
$user->save();
its perfectly saves the user in user table but i want also want to save data in user_role table.
Can you guys please help me how to save this ??
Use attach() method after you create the user:
$user->roles()->attach($roleId);
In User model:
public function roles()
{
return $this->belongsToMany(Role::class);
}
In Role model:
public function users()
{
return $this->belongsToMany(User::class);
}
I assume you pass the roles as an array, then in your controller you can have something like this:
public function store(Request $request)
{
//return $request->roles;
$this->validate($request, [
'name' => 'required|string',
'email' => 'required|email|unique:users',
'password' => 'required|confirmed'
]);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;
$user->save();
$user->roles()->attach($request->roles);
return redirect()->route('backend.users');
}
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.
I have two tables: Account and Transaction.
These tables relate to each other, by Account hasOne Transaction.
i want to show data in Transaction page, once Account was created.
My Account Model
public function transactions()
{
return $this->hasOne(\App\Transaction::class)->latest();
}
My Transaction Model
public function account()
{
return $this->belongsTo(\App\Account::class);
}
And my TransactionController
(I tried to implement code like below, but still no luck):
public function index()
{
$transactions = Transaction::with(['account' => function($query) {
$query->orderBy('id', 'desc')->first();
}]);
return response()->json(['transactions' => $transactions]);
}
Any Help? Thanks.....
QueryBuilder chains need either a get() or a first() or something of that nature at the end to execute the query, right now the variable you're passing to the view is the unexecuted query builder. Try this
$transactions = Transaction::with(['account' => function($query) {
$query->orderBy('id', 'desc')
}])->get();
Although, as TimLewis pointed out in the comments, if the relationship between transactions and accounts is one to one then there's no need to do any ordering of the account so it can just be this
$transactions = Transaction::with('account')->get();
Oooopppp i found what i want....
In my AccountController
public function store(Request $request)
{
$validateData = $request->validate([
'name' => 'required',
'code' => 'required',
]);
$account = new Account();
$account->user_id = auth()->user()->id;
$account->code = $request->code;
$account->name = $request->name;
$account->description = $request->description;
$account->balance = $request->balance;
$account->save();
$transaction = new \App\Transaction();
$transaction->credit = $request->balance;
$account->transaction()->save($transaction);
return response()->json(['created' => true]);
}
i have to save Transaction Relationship with Account.
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();
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}}">
I'm trying to get associate to work.
Relationship on User model:
public function group()
{
return $this->belongsTo('User');
}
So I do:
$user = new User();
//save user fields
....
$user->save();
$group = Group::find(1);
$user->group()->associate($group);
A new user is inserted, but in the FK of group_id on the user table I am getting null.
Associate needs to be before save.
$user = new User();
//save user fields
....
$group = Group::find(1);
$user->group()->associate($group);
$user->save();
Well, let say you want to associate a comment with a blog post, because the comment can only be for a specific post we will use associate.
In our Post model we will have this:
public function comments(){
return $this->hasMany('App\Comment');
}
in our comment model we have this:
public function post(){
return $this->belongsTo('App\Post');
}
In our CommentsController we will have this:
$comment = new Comment;
$post=Post::find($post_id);
$comment->post()->associate($post);
$comment->save();
Pay attention that you save it only after you associate it with the post.
you need to save user after associating
$user->save();
full code
$user = User::create([
'field1' => $request->field1,
....
]);
$group = Group::find(1);
$user->group()->associate($group);
$user->save();