How with jenssegers/mongodb get last Insert Id? - laravel

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.

Related

Laravel Form Request unique field validation on update

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

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 :)

Rollback not working in laravel multiple database in 5.2

Rollback not working in laravel multiple database in 5.2. What can i do? please help me. Advance thanks.
public function TestingRegistration(){
$now=date('Y-m-d H:i:s');
$faculty_user_account=array(
'user_id' =>'466297',
'name' => 'Hello',
);
\DB::beginTransaction();
try{
$save_registration=\DB::table('users')->insert($faculty_user_account);
$view2= \DB::connection('mysql_2')->table('users')->insert($faculty_user_account);
$view3 = \DB::connection('mysql_3')->table('users')->insert($faculty_user_account);
\DB::commit();
return \Redirect::back()->with('message',"Faculty Registration Successfull!");
}catch(\Exception $e){
\DB::rollback();
$message = "Message : ".$e->getMessage().", File : ".$e->getFile().", Line : ".$e->getLine();
return \Redirect::back()->with('errormessage',$message);
}
}
The easy way to do transaction is to use it as a callback, this way it will be handle it automatically for you.
public function TestingRegistration(){
$now = \Carbon::now(); // Where is this use?
$faculty_user_account = [
'user_id' => '466297',
'name' => 'Hello',
];
$success = \DB::transaction(function () use ($faculty_user_account) {
$save_registration = \DB::table('users')->insert($faculty_user_account);
$view2 = \DB::connection('mysql_2')->table('users')->insert($faculty_user_account);
$view3 = \DB::connection('mysql_3')->table('users')->insert($faculty_user_account);
return (bool) $view2 && $view3;
});
if (! $success) {
return \Redirect::back()->with('errormessage', 'Unable to save.');
}
return \Redirect::back()->with('message',"Faculty Registration Successfull!");
}
PS: I can't remember what insert returns, let me check later to make sure it can be use like that for testing success.

Return user info in Sentry2

I want to return the users info to my view when a user logs in but I keep getting an error message that says "Undefined variable: user"
Here is my controller code:
public function postLogin()
{
$credentials = array(
'email' => \Input::get('email'),
'password' => \Input::get('password')
);
try
{
$user = \Sentry::authenticate($credentials, false);
if ($user);
{
$user = \Sentry::getUser();
\Notification::succes('Succesvol ingelogd als,'. $user->name);
return \Redirect::back()-with($user);
}
}
catch(\Exception $e)
{
\Notification::error($e->getMessage());
return \Redirect::back();
}
}
and in my view I try to use the $user variable but then I get the error.
When you do:
Redirect::back()->with('user',$user);
In your new request you must get the user from the Session:
$user = Session::get('user');
and pass it to your view:
return View::make('view')->with('user', $user);
Because Laravel doesn't create global variables as it does when you:
return View::make('view')->with('variableName', $value);

Resources