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

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}}">

Related

Update record using 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.

Error inserting a record using Laravel Cashier and many-to-many relationship

I have a many-to-many relationship between the User and Subscription tables in Laravel, as follows:
In Subscription.php:
public function users()
{
return $this->belongsToMany('App\User')->withTimestamps();
}
In User.php
public function subscriptions()
{
return $this->belongsToMany('App\Subscription')->withTimestamps();
}
I create a new subscription in Cashier (using Stripe) as follows:
$user->newSubscription($planname, $planname)->create();
(Note that the product and plan names are currently the same and the user's card is on record, hence the lack of a stripe token.)
But when I run this I get an error:
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into subscriptions (name, stripe_id, stripe_plan, quantity, updated_at, created_at) values (projects, sub_EY1zRywZ1jUjLl, projects, 1, 2019-02-17 20:07:36, 2019-02-17 20:07:36))
I'm not sure if the relationship is causing the issue or whether it's my new subscription code. How do I fix this error?
UPDATE:
I've made the following change and I still get the same error:
$user->newSubscription($planname, $planname)->create(null,[
'user_id' => $user->id,
]);
UPDATE 2:
I've made the following change and the exact same error still occurs:
$id = Auth::id();
$user = User::find($id);
// $user = Auth::user();
Do you have the Billable trait added to your User model?
General error: 1364 Field 'user_id' doesn't have a default value.
According to this, I think you need to fill the user_id column with an id value via $id = Auth::id();
Taken from laravel documentation:
Additional User Details
If you would like to specify additional customer details, you may do so by passing them as the second argument to the create method:
$user->newSubscription('main', 'monthly')->create($stripeToken, [
'email' => $email,
]);
UPDATE
Could you try this one:
$id = Auth::id();
$user = User::find($id);
$user->newSubscription($planname, $planname)->create();

Laravel 5.6 - Using model functions in ModelFactory

I am working with Laravel 5.6 and found myself a weird problem while extending the functionality of my project.
Right now i need to create two new models: order and item. It was quite easy to fill the items table with dummy data using Faker and Laravel Factories/Seeders. The biggest problem is while working with the order model.
This little fellow is related to a company with a foreign key named company_id and user with a foreign key named seller_id. The company field is okay, the trouble is behind my seller_id
This seller needs a role related to the company my factory will randomly pick for it because the user is not related to the company (directly) and i can't just look for it with a company_id.
In order to get all the users "related" to my company, i've created the next function on my Company model:
public function users()
{
$roles = $this->roles;
$users = [];
foreach ($roles as $role) {
foreach ($role->users as $user) {
$user->makeHidden(['pivot']);
array_push($users, $user);
}
}
$users = array_unique_objects($users);
return $users;
}
btw: I'm using laravel-permissions, a library made by Spatie.
What this functions does is get every role from a company and then it pushes it to an array of users.
This custom helper: array_unique_objects tracks any repeated user on my array and removes them.
That function works find because i've tested on a couple of controllers so i know there is no problem with it. Either way, my OrderFactory.php looks like this:
<?php
use Faker\Generator as Faker;
use App\Models\User;
use App\Models\Company;
$factory->define(App\Models\Order::class, function (Faker $faker) {
$company = Company::get()->random(1);
$users = $company->users();
$user = array_random($users);
return [
'company_id' => $company,
'seller_id' => $user->id,
'code' => strtoupper(str_random(10)),
'description' => $faker->sentence($nbWords = rand(2, 4), $variableNbWords = true),
'created_at' => $faker->dateTimeBetween($startDate = '-1 year', $endDate = 'now', $timezone = null)
];
});
But when i run the php artisan db:seed command, it throws the next error in console:
BadMethodCallException : Method Illuminate\Database\Eloquent\Collection::users does not exist.
at >/home/ironman/Documentos/Sandbox/Proventas/Backend/vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php:99
95| */
96| public function __call($method, $parameters)
97| {
98| if (! static::hasMacro($method)) {
99| throw new BadMethodCallException(sprintf(
100| 'Method %s::%s does not exist.', static::class, $method
101| ));
102| }
103|
Exception trace:
1 Illuminate\Support\Collection::__call("users", [])
/home/ironman/Documentos/Sandbox/Proventas/Backend/database/factories/OrderFactory.php:10
2 Illuminate\Database\Eloquent\Factory::{closure}(Object(Faker\Generator), [])
/home/ironman/Documentos/Sandbox/Proventas/Backend/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:274
Please use the argument -v to see more details.
Is there anything I can do to fix this problem? I know that using Laravel Relationships will fix my problem but the specifications of this project says that i have to keep things just as the are.
Your call to
$company = Company::get()->random(1);
does not return a single company. It returns a Collection, which does not have a users dynamic function. Try
$company = Company::get()->random(1)->first();

How can fill the user id field with auth user on creation of resource?

I'm sure there must be a very simple way to do this - I would like to fill the user_id field on my resource with the authenticated user's id whenever a new instance of the resource is created.
In the store() method of my Resource model I have:
public function store(Request $request)
{
$input = $request->all();
$resource = Resource::create($input);
$resource->user_id = Auth::user()->id;
return $resource;
return 'Resource added.';
}
This works through a post API route, however whenever I add a new resource instance through Nova dashboard, it does not add the Auth user id. I'm guessing this because Nova doesn't use that Resource controller that I have set out?
I would appreciate suggestions!
Working on the assumption that you have relationship method User::resources() the following should work:
return $request->user()->resources()->create($request->all());
The way you have it doesn't work because you didn't save the resource after associating user with it.
I haven't used Nova yet, but since its also laravel and most likely Eloquent ORM I can tell the following.
In these two lines you've set the user_id but you haven't persisted the change:
$resource->user_id = Auth::user()->id;
return $resource;
You should add this line to save the changes you've done:
$resource->save();
As an alternative you could add the value already into your $input array:
$input = $request->all();
$input["user_id"] = Auth::user()->id;
$resource = Resource::create($input);
I just created an ResourceObserver. Saved the Auth()->user->id with the created method.
Registered the ResourceObserver to AppServiceProvider and NovaServiceProvider.
https://laravel.com/docs/5.7/eloquent#observers
https://nova.laravel.com/docs/1.0/resources/#resource-events
In the model class, add function like this:
public function save(array $options = array())
{
$this->user_id = auth()->id();
parent::save($options);
}
Just be carefull if you tend to use save in any other scenario so you don't overwrite existing user_id.

Laravel: Insert in pivot table [duplicate]

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');
}

Resources