I have a problem with create() method in Laravel.
Every time when I try to create new record in database using this code:
$website = Website::create([
'user_id' => auth()->user()->id,
'name' => $request->name,
'url' => $request->url,
'description' => $request->description,
'subcategory_id' => $request->subcategory_id,
'user_id' => $request->subcategory_extra_id,
]);
the column user_id (in database) equals to 0 whereas my id is 1. Of course I have fillable variable in my model:
protected $fillable = [
'user_id',
'name',
'url',
'description',
'subcategory_id',
];
I tried to use constant value instead of auth()->user()->id but I still have 0 as user_id in database. Using save() method solves this problem but I prefer to use create().
You have listed user_id twice in your keys. The 2nd time, the integer is empty.
'user_id' => $request->subcategory_extra_id,
//observe
Why you used 'user_id two times in your code?
one is
'user_id' => auth()->user()->id,
and another one is
'user_id' => $request->subcategory_extra_id,
Just use one instead of two. And try to use the follwing way:
'user_id' => Auth::user()->id;
Remember: in this case you have to use the namespace of Auth class.
Hope it will work
try to use this
use Auth namespace
and then
$website = Website::create([
'user_id' => Auth::user()->id,
'name' => $request->name,
'url' => $request->url,
'description' => $request->description,
'subcategory_id' => $request->subcategory_id,
]);
Related
this is my controller
$rules = [
'Group_Id'=>'required',
'Group_Code'=>'required',
'Group_Name'=>'required| string',
'Currency'=>'required',
'Country'=>'required',
'State'=>'required',
'City'=>'required',
]
I want group id Group code should be unique while create if group id /group code already present in table means I want to print error as group id/group id already exit .while updating don't want to change group id filed that's remains same
$rules = [
'Group_Id'=>'required|unique:group,id',
'Group_Code'=>'required|unique:group,code',
'Group_Name'=>'required| string',
'Currency'=>'required',
'Country'=>'required',
'State'=>'required',
'City'=>'required',
]
For solving this issue you should add unique identifier in your validation method mentioned as below
$data = $request->validate([
'Group_Id' => 'required',
'Group_Code' => 'required|unique:table_name_here',
'Group_Name' => 'required| string',
'Currency' => 'required',
'Country' => 'required',
'State' => 'required',
'City' => 'required',
]);
I am building a complaint management system and I configure mailtrap in laravel to send mails. What I want is when the user adds a new complaint then there will be automatically sent a 'new complaint' email to the admin. I wrote a simple code in the add new complaint function in the controller but when I run the app there is an error that I don't understand.
TypeError
Argument 1 passed to Illuminate\Database\Eloquent\Builder::create() must be of the type array, object given, called in C:\xampp\htdocs\Complain-Management-System\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php on line 23
This is my create function:
public function create(Request $data)
{
// dd($data['user_id']);
$data->validate([
'type' => 'required',
'station' => 'required',
'description' => 'required|min:20|max:1000',
]);
Complaint::create([
'type' => $data['type'],
'station' => $data['station'],
'description' => $data['description'],
'comment' => $data['comment'],
'status' => $data['status'],
'user_id' => $data['user_id']
]);
$complaint = Complaint::create($data);
Mail::send('emails.test', $complaint->toArray(),function($message) {
$message->to('tm.talhamaqsood18#gmail.com', 'Test Mail')
->subject('Complaint Created');
});
return redirect()->route('all-complaints');
}
And this is the route:
Route::post('complaints', [App\Http\Controllers\ComplaintController::class, 'create'])->name('new-complaint')->middleware('loggedIn');
If Complaint is an Eloquent Model you need to pass an array to create not a Request object, $data is a Request. Not sure why you are trying to create 2 complaints (I assume from the same data).
If you need the newly created Complaint model just assign it to $complaint after you create it with the array:
$complaint = Complaint::create([
'type' => $data['type'],
'station' => $data['station'],
'description' => $data['description'],
'comment' => $data['comment'],
'status' => $data['status'],
'user_id' => $data['user_id']
]);
No need for the other call to Complaint::create you have.
I have a BlogImage model and a Blog model. Now I want to know if it's correct to use the create method with the relation and why it is used this way like below:
$blogImage = new BlogImage();
$blogImage->blog()->create([
//this is making the blog for me
'title' => $request->title,
'content' => $detail,
'category_id' => $request->category_id,
'author' => Auth::user()->id,
'meta_description' => $request->title,
'meta_image' => $meta_image,
]);
Also, I want to know what is the difference between this method and the normal form, which is:
Blog::create([
'title' => $request->title,
'content' => $detail,
'category_id' => $request->category_id,
'author' => Auth::user()->id,
'meta_description' => $request->title,
'meta_image' => $meta_image,
]);
In short: in the first example you're creating the Blog instance and linking it to blogImage, but in the second example you're only creating an instance of the Blog model.
In the second example you would have to attach the new Blog instance to blogImage after creating it with $blogImage->blog()->attach($blog->id).
The first example's create method is described here and the second example's is described here in Laravel's documentation.
Either method is correct. It's just shorter to use the first example.
I have 2 tables within one function that I'd like to save data to. One is the Users table, and the second one is a Clinic table.
My user's table is currently working correctly, but I'm unsure if it's 'best practice':
$user = User::create([
'name' => Str::title($request->get('name')),
'email' => $request->get('email'),
'password' => bcrypt($request->get('password'))
])
->clinic()->create($request->only([
'name' => Str::title('clinic_name'),
'telephone',
'address_1',
'address_2',
'city',
'postcode'
]));
My problem occurs at the 'name' column of the Clinic table. It just doesn't save it, even though it's in the $fillable array in my Clinic column:
protected $fillable = ['user_id', 'name', 'telephone'', 'address_1',
'address_2', 'city', 'postcode'];
I have attempted to 'Chain' the methods together, as I want to save the 'user_id' within the Clinic table because they're related.
Many thanks for your help.
You're overriding the name key in your $request->only() call:
$user = User::create([
'name' => Str::title($request->get('name')),
'email' => $request->get('email'),
'password' => bcrypt($request->get('password'))
])->clinic()->create($request->only([
'name' => Str::title('clinic_name'), // This is overriding your 'name' field.
'telephone',
'address_1',
'address_2',
'city',
'postcode'
]));
If you want to run Str::title() over the requests clinic_name, you'll need to assign the attributes manually like so:
$user = User::create([
'name' => Str::title($request->get('name')),
'email' => $request->get('email'),
'password' => bcrypt($request->get('password'))
])->clinic()->create([
'name' => Str::title($request->get('clinic_name')),
'telephone' => $request->get('telephone'),
'address_1' => $request->get('address_1'),
'address_2' => $request->get('address_2'),
'city' => $request->get('city'),
'postcode' => $request->get('postcode'),
]);
Note: Just as a tip, you can also just retrieve request input as a property like so:
->create([
'name' => $request->name // Performs $request->get('name').
])
You can't have 'name' => Str::title('clinic_name') when using create(), it must be a single key as 'name'.
You can use the following before creating the user:
$request->replace('name' => Str::title('clinic_name'));
Hi i have the next code for create my records
Institution::create($request->all());
User::create([
'name' => $request['name'],
'lastname' => $request['lastname'],
'phone' => $request['phone'],
'email' => $request['email'],
'password' => $request['password'],
'state' => 1,
'profile_id' => 1,
'institution_id' => Institution::max('id'),
]);
The last attributes for the User thats correct implement so?
The last 3 user attributes , it is correct to do it that way? or is there a better
Using Institution::max('id') creates a race condition. Since the create() static method of Eloquent::Model returns the newly-created model, you can just do:
$institution = Institution::create($request->all());
User::create([
'name' => $request['name'],
'lastname' => $request['lastname'],
'phone' => $request['phone'],
'email' => $request['email'],
'password' => $request['password'],
'state_id' => 1,
'profile_id' => 1,
'institution_id' => $institution->id,
]);
Creating a record with known parent ids is generally fine if your goal is to minimize the number of database queries and you have the ids of the related models.
Another way to do it, though it triggers more update queries, is to use Eloquent's built-in methods for adding related models. For example:
$institution = Institution::create($request->all());
$state = State::find(1);
$profile = Profile::find(1);
$user = new User([
'name' => $request['name'],
'lastname' => $request['lastname'],
'phone' => $request['phone'],
'email' => $request['email'],
'password' => $request['password']
]);
$user->state()->associate($state);
$user->profile()->associate($profile);
$user->profile()->associate($institution);
$user->save();
However, in this situation, since the related models are not already loaded, and you know their ids, there is no need to fetch them only to associate them with the User.