Route [dealer] not defined. in laravel? - laravel

I defined my route but it is not showing that Route [dealer] not defined.
Route::resource('/dealer', DealerController::class);
This is my controller where there is index, create and store method is in same page.
public function index()
{
$users = User::all();
return view('dealer', compact('users'));
}
public function create()
{
$dealers = Dealer::all();
return view('dealer', compact('dealers'));
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required',
'password' => 'required',
'name_of_firm' => 'required',
'address' => 'required',
'number' => 'required',
]);
$user = User::create([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => Hash::make($request->input('password')),
'name_of_firm' => $request->input('name_of_firm'),
'address' => $request->input('address'),
'number' => $request->input('number'),
]);
return redirect()->route('dealer')->withSuccess('done');
}

https://laravel.com/docs/8.x/controllers#actions-handled-by-resource-controller
Look at the example from the documentation. There exists no such route in your ressource controller.
Depending on what you want you either have to use dealer.index, dealer.show or dealer.edit
Normally you would also use the plural form and not the singular form of the word.

Related

User create and update using updateOrCreate()

I am creating and updating user using below code.
public function store(Request $request)
{
if ($request->ajax()) {
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users,email,' .$request->user_id,
'password' => 'required',
'role' => 'required',
]);
$user = User::updateOrCreate(['id' => $request->user_id],
[
'name' => $request->name,
'email' => $request->email,
'role' => $request->role,
'password' => Hash::make($request->password)
]);
}
}
When I am updating record Password is updating also. How can I solve the issue ?
How validation is working here 'email' => 'required|email|unique:users,email,' .$request->user_id, when I am creating a record ? Because when I am creating a record at that time $request->user_id is not available.

Laravel Spatie Medialibrary: upload multiple images through REST API

I'm using the Spatie MediaLibrary library in a Laravel application. I want to upload 0 or more photos to my app via a REST API.
I can get it to work when the photo attribute contains 1 file
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'slug' => 'required',
'description' => 'required',
'price' => 'required|integer',
'photo' => 'nullable|file'
]);
$listing = Listing::Create([
'user_id' => auth('api')->user()->id,
'name' => $request->name,
'slug' => $request->slug,
'description' => $request->description,
'price' => $request->price,
]);
// stores the photo
if ($request->hasFile('photo')) {
$listing->addMediaFromRequest('photo')->toMediaCollection('photos');
}
return new ListingResource($listing);
}
The postman request looks as follows:
I know want to change the code so it can handle multiple photos in the request. I'm using the following code in the controller above to do so:
if ($request->hasFile('photo')) {
foreach ($request->input('photo', []) as $photo) {
$listing->addMediaFromRequest('photo')->toMediaCollection('photos');
}
}
and I have changed the attribute to photos[] instead of photo.
The code never goes into the foreach loop even.
Anyone has a hint on how to solve this?
Apparently the Spatie Medialibrary has a function called addMultipleMediaFromRequest. The full code is now
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'slug' => 'required',
'description' => 'required',
'price' => 'required|integer',
'photo' => 'nullable'
]);
$listing = Listing::Create([
'user_id' => auth('api')->user()->id,
'name' => $request->name,
'slug' => $request->slug,
'description' => $request->description,
'price' => $request->price,
]);
if ($request->hasFile('photo')) {
$fileAdders = $listing->addMultipleMediaFromRequest(['photo'])
->each(function ($fileAdder) {
$fileAdder->toMediaCollection('photos');
});
}
return new ListingResource($listing);
}
In Postman, I'm calling it as follows:
documentation reference
I managed to upload multiple files like this:
if($request->file('photos')) {
foreach ($request->file('photos') as $photo) {
$post->addMedia($photo)->toMediaCollection('post');
}
}
Check this out:
https://github.com/spatie/laravel-medialibrary/issues/227#issuecomment-220794240
This code is working for me.
View
<input type="file" name="photo[]" multiple />
ListingController
public function store(Request $request)
{
if ($request->hasFile('photo')) {
$fileAdders = $listing->addMultipleMediaFromRequest(['photo'])
->each(function ($fileAdder) {
$fileAdder->toMediaCollection('photos');
});
}
}

Data isn't inserting into different tables from one form

I'm trying to submit data from one form into two different tables, but it is not submitting, my form contains on two parts one is model, i.e., when modal form submit then its data saves into one table and rest of other data into another table.
Controller
public function store(Request $request)
{
$request->validate([
'patient_fname' => 'required',
'patient_lname' => 'required',
'patient_email' => 'required',
'patient_dob' => 'required',
'patient_guardian' => 'required',
'patient_gender' => 'required',
'user_id' => 'required',
'patient_name' => 'required',
'patient_insurance' => 'required',
'patient_insurance_id' => 'required',
'patient_reason' => 'required',
'patient_new' => 'required',
'patient_contact_no' => 'required',
'patient_message' => 'required',
]);
$userdata = Userdata::create([
Input::get('patient_fname'),
Input::get('patient_lname'),
Input::get('patient_email'),
Input::get('patient_dob'),
Input::get('patient_guardian'),
Input::get('patient_gender')
]);
$form = Form::create([
Input::get('patient_name'),
Input::get('patient_insurance'),
Input::get('patient_insurance_id'),
Input::get('patient_reason'),
Input::get('patient_new'),
Input::get('patient_contact_no'),
Input::get('patient_message')
]);
return back();
}
form.php
protected $guarded = [];
protected $table = "forms";
protected $fillable=['patient_name',
'patient_insurance','patient_insurance_id', 'patient_reason',
'patient_new', 'patient_message'];
public function userdata()
{
return $this->belongsTo('App\Userdata');
}
userdata.php
protected $fillable = ['patient_fname', 'patient_lname',
'patient_email', 'patient_dob', 'patient_guardian',
'patient_gender','user_id'];
public function form()
{
return $this->hasMany('App\Form');
}
I would imagine this is because you're not supplying a key for the values in your create method.
Also, validate will return an array of the validated properties so you can just use that instead of using Input::get():
public function store(Request $request)
{
$data = $request->validate([
'patient_fname' => 'required',
'patient_lname' => 'required',
'patient_email' => 'required',
'patient_dob' => 'required',
'patient_guardian' => 'required',
'patient_gender' => 'required',
'user_id' => 'required',
'patient_name' => 'required',
'patient_insurance' => 'required',
'patient_insurance_id' => 'required',
'patient_reason' => 'required',
'patient_new' => 'required',
'patient_contact_no' => 'required',
'patient_message' => 'required',
]);
$userdata = Userdata::create([
'patient_fname' => $data['patient_fname'],
'patient_lname' => $data['patient_lname'],
'patient_email' => $data['patient_email'],
'patient_dob' => $data['patient_dob'],
'patient_guardian' => $data['patient_guardian'],
'patient_gender' => $data['patient_gender'],
]);
$form = Form::create([
'patient_name' => $data['patient_name'],
'patient_insurance' => $data['patient_insurance'],
'patient_insurance_id' => $data['patient_insurance_id'],
'patient_reason' => $data['patient_reason'],
'patient_new' => $data['patient_new'],
'patient_contact_no' => $data['patient_contact_no'],
'patient_message' => $data['patient_message'],
]);
return back();
}

Find duplicates in Laravel Eloquent

The following code I have on the controller is below.
public function add(Request $request)
{
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required',
]);
$researcherToProject = new ProjectResearchers();
$researcherToProject->user_id = $request->userSelected;
$researcherToProject->project_id = $request->projectSelected;
$researcherToProject->created_at = Carbon::now();
$researcherToProject->updated_at = Carbon::now();
$researcherToProject->save();
return new ProjectsResearchersResource($researcherToProject);
}
Should I make another validation or create a function?
Ex: I create a user id "5" with project id "13" and user id "2" with project id "17". If I try creating again a user id "5" with project id "13" it allows me, so I get two times the same data in the database. How do I avoid duplicate entries?
You can do it using updateOrCreate method, the first array is the unique values that you are looking for, if not found it will create the entry, if it finds them it will just update the fields in the second array so do this instead:
public function add(Request $request){
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required',
]);
$researcherToProject = ProjectResearchers::updateOrCreate(
['user_id' => $request->userSelected, 'project_id' => $request->projectSelected],
['created_at' => Carbon::now(), 'updated_at' => Carbon::now()]
);
return new ProjectsResearchersResource($researcherToProject);
}
or if you don't want to update at all, you can just check if it exists before storing:
public function add(Request $request){
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required',
]);
$researcherToProject = new ProjectResearchers();
if( ! ProjectResearchers::where('user_id', $request->userSelected)->where('project_id', $request->projectSelected)->exists()) {
$researcherToProject = new ProjectResearchers();
$researcherToProject->user_id = $request->userSelected;
$researcherToProject->project_id = $request->projectSelected;
$researcherToProject->created_at = Carbon::now();
$researcherToProject->updated_at = Carbon::now();
$researcherToProject->save();
} else {
$researcherToProject = ProjectResearchers::where('user_id', $request->userSelected)->where('project_id', $request->projectSelected)->first();
}
return new ProjectsResearchersResource($researcherToProject);
}
Additionaly to #nakov answer:
firstOrCreate() can combine 2 ways and looks cleaner:
public function add(Request $request){
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required',
]);
$researcherToProject = ProjectResearchers::firstOrCreate([
'user_id' => $request->userSelected,
'project_id' => $request->projectSelected
]);
$researcherToProject->created_at = Carbon::now();
$researcherToProject->updated_at = Carbon::now();
$researcherToProject->save();
return new ProjectsResearchersResource($researcherToProject);
}
Or if you don't want to update:
public function add(Request $request){
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required',
]);
$researcherToProject = ProjectResearchers::firstOrCreate([
'user_id' => $request->userSelected,
'project_id' => $request->projectSelected
]);
if(!$researcherToProject->id){
$researcherToProject->created_at = Carbon::now();
$researcherToProject->updated_at = Carbon::now();
$researcherToProject->save();
}
return new ProjectsResearchersResource($researcherToProject);
}
change the following:
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required',
]);
to
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required|unique:ProjectResearchers,project_id,NULL,id,user_id,'.$request->userSelected
]);
this will work check if the combination of user-project already exists inthe table called ProjectResearchers.
for more information about the unique validation rule visit the Laravel Documentation.

How to forcing a unique rule to ignore a given id?

While updating the "users" table, I want the EditUserRequest form checkout to ignore the current email because it already exists.
Code rules:
public function rules()
{
return [
'username' => 'required|max:200',
'email' => [
'required',
Rule::unique('users')->ignore($user->id),
],
'pass1' => 'required|min:6',
'pass2' => 'same:pass1',
];
}
Code UserController:
public function postEdit($id,EditUserRequest $request)
{
$user = User::find($id);
$user->name = $request->username;
$user->email = $request->email;
$user->password = Hash::make($request->pass1);
$user->level = $request->get('cbadmin',0);
$user->save();
return view('admin.edit-user')->with('success','Sửa thành công!');
}
This line: 'email' => 'required|email|unique:users,email' will check email exists. However, the default email I need to update it already exists. Did I read:https://laravel.com/docs/5.6/validation#rule-unique. But I do not understand how to solve this problem
public function rules()
{
return [
'username' => 'required|max:200',
'email' => 'required|email|unique:users,email,'.request()->user()->id,
'pass1' => 'required|min:6',
'pass2' => 'same:pass1',
];
}
You can pass a third parameter as id to ignore.
Hope this helps.
I am not sure of your route parameter names since your routes aren't included in the post, so I will assume $id on the controller method means there is a route parameter named id.
'email' => [
'required',
Rule::unique('users')->ignore($this->route('id')),
],
This would use the id from the route parameter, assuming it was named id. This will tell the rule to ignore the unique check on this email field for this particular User id.
you can do this by using the Rule facade ..
'email' => [
'required',
Rule::unique('users')->ignore($user->id),
],
EDIT
in case you're using a function to validate your inputs you may do it like this:
protected function yourValidatorName(array $data, $id)
{
return Validator::make($data, [
'username' => 'required|max:200',
'email' => [
'required',
Rule::unique('users')->ignore($id),
],
'pass1' => 'required|min:6',
'pass2' => 'same:pass1',
]);
}
then
public function postEdit($id, EditUserRequest $request)
{
$accountValidate = $this->yourValidatorName($request->all(), $id);
if (!$accountValidate->fails())
{
// success
}
else
{
// failed
}
}
Can you show me your route for postEdit?
For example this is your route:
Route::put('users/{user_id_sample}', 'UserController#postEdit');
You may do something like this:
public function rules()
{
return [
'username' => 'required|max:200',
'email' => [
'required',
Rule::unique('users')->ignore($this->route('user_id_sample')),
],
'pass1' => 'required|min:6',
'pass2' => 'same:pass1',
];
}

Resources