Laravel Form Request unique field validation on update - laravel

I have to make Form Request and have a unique rule on the title. How to ignore unique validation for updating id?
These are my rules when I try to get an id passed from the controller.
public function rules()
{
$id = $this->request->get('id') ? ',.' $this->request->get('id') : '';
$rules = [
'title' => 'required|min:3|unique:parent_categories',
];
if ($this->getMethod() == 'PUT' || $this->getMethod() == 'PATCH') {
$rules += ['title' => 'required|min:3|unique:parent_categories,title' . $id];
}
return $rules;
}
This is my controller where I am trying to update content with id.
public function update(ParentCategoryRequest $request, $id)
{
DB::beginTransaction();
try {
$parentCategory = ParentCategory::update($id, $request->all());
DB::commit();
return $this->success('Parent category updated successfully', new ParentCategoryResource($parentCategory), 201);
} catch (Exception $e) {
DB::rollBack();
return $this->error($e->getMessage(), $e->getCode());
}
}
I am getting...
undefined variable $id on ParentCategoryRequest

Related

How with jenssegers/mongodb get last Insert Id?

On Laravel site using jenssegers/mongodb I have store method like :
public function store(ItemRequest $request)
{
$request = request();
try {
$session = DB::getMongoClient()->startSession();
$session->startTransaction();
$insertData = $request->all();
$insertData['published'] = ! empty($insertData['published']);
$item = Item::create([
'title' => $insertData['title'],
'text' => $insertData['text'],
'published' => $insertData['published'],
]);
$session->commitTransaction();
} catch (Exception $e) {
$session->abortTransaction();
return back()->withErrors(['message' => $e->getMessage()]);
}
return redirect(route('admin.items.edit', $item->_id))
->with('message', 'New item was successfully added')
->with('message_type', 'success');
}
But making test for this controller method I did not find how to get ID on new ite, generated on mongodb site :
public function testIsItemEditFormSubmittedWithSuccess()
{
$this->withoutMiddleware();
$item = \App\Models\Item::factory(Item::class)->make();
// Test Action
$response = $this->actingAs(self::$loggedAdmin, 'web')->post(route('admin.items.store'), $item->toArray());
$newItemId = DB::getPdo()->lastInsertId();
// If to uncomment line above I got "Error: Call to a member function lastInsertId() on null"
$response->assertStatus(302); // Redirection status
$response->assertRedirect(route('admin.items.edit', [???])); // HOW can New ID on "store" method above ?
$response->assertSessionHasNoErrors();
}
Any equvalent of lastInsertId for jenssegers/mongodb ?
"jenssegers/mongodb": "^3.9.2",
"laravel/framework": "^9.30.1",
Thanks in advance!
Check this issue.
https://github.com/jenssegers/laravel-mongodb/issues/2451
Your laravel should be 9.31. So downgrade it to 9.30 and wait next release.

delete image from desk and table in morph relation in laravel

i have many to many morph relation in laravel and i want to update model that have images in attachmnets table
my Specialization model
public function attachments()
{
return $this->morphToMany(Attachment::class, 'attachmentable');
}
my Attachment model
public function specializations()
{
return $this->morphedByMany(Specialization::class, 'attachmentable');
}
my attachmentables model
protected $fillable = [
'attachment_id',
'attachmentable_id',
'attachmentable_type',
'key',
];
my controller update function
public function updatee($request, $id){
if($request->hasfile('image')){
$image = $this->uploadImages($request->image , 'specialiations/images');
$specialization = Specialization::where('id',$id)->with('attachments')->first();
if($specialization != null){
$this->attachmentRepository->destroy($specialization->attachments[0]->id, $request);
try {
unlink(public_path().$request->file);
} catch (\Throwable $th) {
//throw $th;
}
}
$spec = $this->update($request->all(),$id,$request);
$specImage = $this->attachmentRepository->create(['file'=>$image]);
$att = $this->attachmentAbleRepository->create([
'attachment_id' => $specImage->id,
'attachmentable_id' => $spec->id,
'attachmentable_type' => 'App\Models\Specialization',
'key' => 'specialization',
]);
}
return $spec;
}
i have an error "Undefined array key 0" or "attempt [id]"

GuzzleHttp\Exception\InvalidArgumentException IDN conversion failed

after i added product data into database, this error page show me instead of routing to product page.
But, data is successful inserted.
ProductsController.php
public function store(Request $request)
{
$slug = $this->getSlug($request);
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$this->authorize('add', app($dataType->model_name));
// Validate fields with ajax
$val = $this->validateBread($request->all(), $dataType->addRows);
if ($val->fails()) {
return response()->json(['errors' => $val->messages()]);
}
if (!$request->ajax()) {
$requestNew = $request;
$requestNew['price'] = $request->price * 100;
$data = $this->insertUpdateData($requestNew, $slug, $dataType->addRows, new $dataType->model_name());
event(new BreadDataAdded($dataType, $data));
$this->updateProductCategories($request, $data->id);
return redirect()
->route("voyager.{$dataType->slug}.index")
->with([
'message' => __('voyager.generic.successfully_added_new')." {$dataType->display_name_singular}",
'alert-type' => 'success',
]);
}
}
Plz help me

How To Create Conditional for Unique Validation (UPDATE/PATCH) on Form Request

I'm trying to get my controller cleaner by moving 'validation request' into a form request called 'BookRequest'.
The problem is on the update process, I try to create a condition to check, if it PATCH or POST with the following codes
MyRequest.php
public function rules()
{
// Check Create or Update
if ($this->method() == 'PATCH')
{
$a_rules = 'required|string|size:6|unique:books,column2,' .$this->get('id');
$b_rules = 'sometimes|string|size:10|unique:books,column3,' .$this->get('id');
}
else
{
$a_rules = 'required|string|size:6|unique:books,column2';
$b_rules = 'sometimes|string|size:10|unique:books,column3';
}
return [
'column1' => 'required|string|max:100',
'column2' => $a_rules,
'column3' => $b_rules,
'column4' => 'required|date',
'column5' => 'required|in:foo,bar',
'column6' => 'required',
'column7' => 'required',
'column8' => 'required',
];
}
.$this->get('id') it failed, the form still treat the unique on the update.
Controller#update
public function update($id, BookRequest $request)
{
$book = Book::findOrFail($id);
$input = $request->all();
$book->update($request->all());
return view('dashboards.book');
}
Controller#edit
public function edit($id)
{
$book = Book::findOrFail($id);
return view('dashboards.edit', compact('book'));
}
Controller#create
public function create()
{
return view('dashboards.create');
}
Controller#store
public function store(BookRequest $request)
{
$input = $request->all();
$book = Book::create($input);
return redirect('dashboards/book/index');
}
I try the alternative .$book->id, and it throw me an ErrorException Undefined variable: book
Any suggestion? I'm using Laravel 5.2 by the way
You are using book as your route parameter but trying to get with id. try this-
if ($this->method() == 'PATCH')
{
$a_rules = 'required|string|size:6|unique:books,column2,' .$this->route()->parameter('book');
$b_rules = 'sometimes|string|size:10|unique:books,column3,' .$this->route()->parameter('book');
}
Hope it helps :)

Laravel not redirecting to route

I'm trying to validate some data from a form and redirect the user to the page with any errors if any. My code doesn't redirect to any route. The routing for all of my routes works correctly. I echoed the input with Input::all() and it does have the user input. The validator works as well. I'm not sure exactly what's preventing the Redirect::route from working
public function postPurchase()
{
$validator = Validator::make(Input::all(), array(
'condition' => 'required',
'memory' => 'required',
'color' => 'required',
'accessories' => 'required',
'shipping' => 'required'
));
// $input = Input::all();
// dd($input);
if ($validator->fails()) {
// echo "string";
return Redirect::route('home');
} else {
echo "this succedded";
}
//Get prices, item id, etc and send user to checkout page
// echo "Get prices, item id, etc and send user to checkout page";
}
This is the code that precede the postPurchase method:
public function getPurchase()
{
return View::make('general.purchase');
}
public function getCheckout()
{
return View::make('general.checkout');
}
public function postPurchaseCheck()
{
$input = Input::all();
$this->input = $input;
if (Input::get('buy')) {
$this->postPurchase();
}
elseif (Input::get('cart')) {
$this->postAddCart();
}
}
You call the function - but you dont 'return' the Redirect that is given back to you.
Change
if (Input::get('buy')) {
$this->postPurchase();
}
to
if (Input::get('buy')) {
return $this->postPurchase();
}
Try updating this
if (Input::get('buy')) {
return $this->postPurchase();
} elseif (Input::get('cart')) {
return $this->postAddCart();
}
and
if ($validator->fails()) {
// echo "string";
return Redirect::to('home');
} else {
echo "this succedded";
}
also don't forget to define it on route file
Change you postPurchaseCheck() method to return what is returned by $this->postPurchase() like this. Because you are calling the postPurchase() method internally but post is happening on postPurchaseCheck() method so redirect has to be returned by the method that handle POST request
public function postPurchaseCheck()
{
$input = Input::all();
$this->input = $input;
if (Input::get('buy')) {
return $this->postPurchase();
}
elseif (Input::get('cart')) {
return $this->postAddCart();
}
}

Resources