Find duplicates in Laravel Eloquent - laravel

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.

Related

Route [dealer] not defined. in 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.

I want to redirect after complete both insert from Laravel request

so I have this store function at my Controller
public function store(Request $request)
{
Penghuni::create([
'nama_penghuni' => $request->nama_penghuni,
'email' => $request->email,
'phone' => $request->phone,
'tower' => $request->tower,
'no_unit' => $request->no_unit
]);
User::create([
'name' => $request->nama_penghuni,
'email' => $request->email,
'password' => Hash::make($request['password']),
'role' => 'penghuni',
]);
return redirect(route('penghuni.index'));
}
what I want is make sure both insert is success, because the current result I got is when Penghuni create is done but the user is fails it keeps getting redirected
hope someone can help, I use laravel 5.8
thank you
This Code is Perfect check other things.
public function store(Request $request)
{
Penghuni::create([
'nama_penghuni' => $request->nama_penghuni,
'email' => $request->email,
'phone' => $request->phone,
'tower' => $request->tower,
'no_unit' => $request->no_unit
]);
User::create([
'name' => $request->nama_penghuni,
'email' => $request->email,
'password' => Hash::make($request['password']),
'role' => 'penghuni',
]);
return redirect(route('penghuni.index'));
}
1. Model
Penghuni and user Model must added this Line
protected $guarded = [];
Other Solution
public function store(Request $request)
{
$penghuni = new Penghuni;
$penghuni->nama_penghuni = $request->nama_penghuni;
$penghuni->email = $request->email;
$penghuni->phone = $request->phone;
$penghuni->tower = $request->tower;
$penghuni->no_unit = $request->no_unit;
$penghuni->save();
$user = new User;
$user->name = $request->nama_penghuni;
$user->email = $request->email;
$user->password = Hash::make($request->password);
$user->role = 'role';
$penghuni->users()->save($user);
return redirect(route('penghuni.index'));
}
You can wrap your queries in a database transaction like so:
DB::transaction(function () use ($request) {
// queries here
});
return redirect(route('penghuni.index'));
Or something like this, depending on your use-case.
DB::beginTransaction();
try {
// queries here
// all good
DB::commit();
return redirect(route('penghuni.index'));
} catch (\Exception $e) {
// something went wrong
DB::rollback();
}
You can read more about database transaction here: https://laravel.com/docs/8.x/database#database-transactions

image isn't saving into db in laravel

hi m trying to save data into db data saves but image isn't saving how to save it in db:
controller:
public function store(Request $request)
{
// dd($request->all());
$request->validate([
'category_name' => 'required',
'category_description' => 'required',
'category_slug' => 'required',
'category_image' => 'required|image',
]);
DB::table('categories')->insert([
'category_name' => $request->category_name,
'category_description' => $request->category_description,
'category_slug' => $request->category_slug,
'category_image' => $request->category_image,
]);
$path = $request->file('category_image');
$path->getClientOriginalName();
$path->move(public_path('images/backend_images/category_images');
return back();
}
Well... In your portion of code, there is no var.save(); so how will eloquent store any data without the given instruction?
Per example do something like this:
$userImage = new UserImage;
$UserImage->save();
public function store(Request $request)
{
// dd($request->all());
$request->validate([
'category_name' => 'required',
'category_description' => 'required',
'category_slug' => 'required',
'category_image' => 'required|image',
]);
$path = $request->file('category_image');
$nameImage = $path->getClientOriginalName();
$path->move(base_path('public/images/backend_images/category_images'), $nameImage);
DB::table('categories')->insert([
'category_name' => $request->category_name,
'category_description' => $request->category_description,
'category_slug' => $request->category_slug,
'category_image' => $nameImage,
]);
return redirect()->back();
}
code in my project and its work!
if ($request->hasFile('image')) {
$file = $request->file('image');
$filename = date('mdYHis') .str_random(5).'.'.$file->extension();
$request->image->move(base_path('public/images/rooms'), $filename);
$request->merge(array('image' => $filename));;
}
I think this would help. But you can browse for more answers.
Save to public directory
$path = 'images/backend_images/category_images';
$file = $request->file('category_image');
$filename = $file->getClientOriginalName();
$file->move(public_path($path), $filename);
And the, save to database
DB::table('categories')->insert([
'category_name' => $request->category_name,
'category_description' => $request->category_description,
'category_slug' => $request->category_slug,
'category_image' => $filename
]);

Validation error in api response in laravel 5.6

I want to store data through api. It's working but problem is when I add validation it does not give me corresponding message . How can I fix it? Thanks in advance
Here is my route
Route::post('api/add_user', 'TestApiController#store');
Here is my controller
public function store(Request $request)
{
$validation = Validator::make(Request::all(), [
'name' => 'required',
'phone' => 'required',
'email' => 'required'
]);
if ($validation->errors()) {
return $errors->toJson();
} else {
$testApi = new testApi();
$testApi->name = $request->name;
$testApi->phone = $request->phone;
$testApi->email = $request->email;
$testApi->save();
return "ok";
}
}
to handle that your method should be like this :
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'phone' => 'required',
'email2' => 'required|email'
]);
if($validator->fails()){
// here we return all the errors message
return response()->json(['errors' => $validator->errors()], 422);
}
$testApi = new testApi();
$testApi->name = $request->name;
$testApi->phone = $request->phone;
$testApi->email = $request->email;
$testApi->save();
// 201 http code means that the server has proceced your request correctly
return response()->json([], 201);
}
You don't have to manually do this. simply
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'phone' => 'required',
'email' => 'required'
]);
$testApi = new testApi();
$testApi->name = $request->name;
$testApi->phone = $request->phone;
$testApi->email = $request->email;
$testApi->save();
return "ok";
}
this will automatically handles validation and returns error message when invalid.
Update
if you wanna stick with your approach. this is where you need to change.
if ($validation->fails()) {
return $validation->errors();
}

use cookie to store and retrieve order data in laravel

use cookie to store and retrieve order data in laravel
I want to use cookie to store and retrieve order data in store order:
public function store(Request $request, $serviceId) {
$request->validate([
'company_id' => 'required',
'user_id' => 'required',
'individual_count' => 'required',
'date' => 'required',
'time' => 'required',
'total_price' => 'required',
'is_home' => 'required',
]);
$request['date'] = date('Y-m-d H:i:s', strtotime($request->date . $request->time));
$request['total_price'] = explodeBySpace($request->total_price)[0];
$request['service_id'] = Hashids::decode($serviceId)[0];
session([ 'totalOrderPrice' => $request['total_price'] ]);
session([ 'companyName' => $request->company_name ]);
session([ 'individualCount' => $request->individual_count ]);
session([ 'orderDate' => $request['date'] ]);
// dd($request->all());
$created = Orders::create($request->all());
if ($created) {
session(['orderId' => $created->id]);
Cookie::make('orderId', $created->id, 180); // ?
return redirect()->route('payment.method');
}
return redirect()->route('web.orders.create', $serviceId)->with('alert', 'error');
}
to retrieve order data for payment operation :
public function storeReceipt(Request $request, $method) {
$request->validate([
'price' => 'required|numeric',
]);
$request['order_id'] = $request->cookie('orderId');
$request['method'] = $method;
$created = Payment::create($request->all());
return $created->count() > 0
? redirect()->route('home')->with('alert', 'success')
: redirect()->route('payment/method/create', 'receipt')->with('alert', 'error');
}
but this error occurs
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'order_id' cannot be null
what is the wrong
Hi you can try Cookie::get(); to retrieve the cookies
public function storeReceipt(Request $request, $method) {
$request->validate([
'price' => 'required|numeric',
]);
$request['order_id'] = Cookie::get('orderId');
$request['method'] = $method;
$created = Payment::create($request->all());
return $created->count() > 0
? redirect()->route('home')->with('alert', 'success')
: redirect()->route('payment/method/create', 'receipt')->with('alert', 'error');
}

Resources