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.
Related
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.
The problem is when I entered a new name no data is added. A similar thing happen when I entered an already existing name. Still, no data is added to the database. I am still new to CodeIgniter and not entirely sure my query builder inside the model is correct or not.
In the Model, I check if the name already exists insert data only into the phone_info table. IF name does not exist I insert data into user_info and phone_info.
Controller:
public function addData()
{
$name = $this->input->post('name');
$contact_num = $this->input->post('contact_num');
if($name == '') {
$result['message'] = "Please enter contact name";
} elseif($contact_num == '') {
$result['message'] = "Please enter contact number";
} else {
$result['message'] = "";
$data = array(
'name' => $name,
'contact_num' => $contact_num
);
$this->m->addData($data);
}
echo json_encode($result);
}
Model:
public function addData($data)
{
if(mysqli_num_rows($data['name']) > 0) {
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info',$phone_info);
} else {
$user_info = array(
'name' => $data['name']
);
$this->db->insert('user_info', $user_info);
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info', $phone_info);
}
}
DB-Table user_info:
DB-Table phone_info:
Extend and change your model to this:
public function findByTitle($name)
{
$this->db->where('name', $name);
return $this->result();
}
public function addData($data)
{
if(count($this->findByTitle($data['name'])) > 0) {
//.. your code
} else {
//.. your code
}
}
Explanation:
This:
if(mysqli_num_rows($data['name']) > 0)
..is not working to find database entries by name. To do this you can use codeigniters built in model functions and benefit from the MVC Pattern features, that CodeIgniter comes with.
I wrapped the actual findByName in a function so you can adapt this to other logic and use it elswehere later on. This function uses the query() method.
Read more about CodeIgniters Model Queries in the documentation.
Sidenote: mysqli_num_rows is used to iterate find results recieved by mysqli_query. This is very basic sql querying and you do not need that in a MVC-Framework like CodeIgniter. If you every appear to need write a manual sql-query, even then you should use CodeIgniters RawQuery methods.
i have store function for save data to database and i want redirect to another url with passing $invoice variable
this is my store function :
$order = Order::create([
'no' => $invoice,
'spg' => $request->spg,
'nama' => $request->nama,
'hp' => $request->hp,
'alamat' => $request->alamat,
]);
return redirect('invoicelink', compact('invoice'));
this is my route file:
Route::resource('/', OrderController::class);
Route::get('invoicelink/{invoice}', [OrderController::class, 'invoicelink'])->name('invoicelink');
and this is my invoicelink function:
public function invoicelink($invoice)
{
dd($invoice);
}
How to do it? very grateful if someone help to solve my problem. thanks
If you look at the helper function you are calling, I don't think it is what you are looking for.
function redirect($to = null, $status = 302, $headers = [], $secure = null)
{
if (is_null($to)) {
return app('redirect');
}
return app('redirect')->to($to, $status, $headers, $secure);
}
I think what you want is
Redirect::route('invoiceLink', $invoice);
You can also use the redirect function, but it would look like this
redirect()->route('invoiceLink', $invoice);
You can see this documented here https://laravel.com/docs/8.x/responses#redirecting-named-routes
i found the solution:
web.php
Route::get('invoicelink/{invoice}', [OrderController::class, 'invoicelink'])->name('invoicelink');
controller:
public function invoicelink($invoice)
{
//dd($invoice);
return $invoice;
}
then use redirect:
return redirect()->route('invoicelink', [$invoice]);
I'm migrating my old system to the new version of Laravel, and I'm having problems with one of my requests...
Basically on this request I receive any file and simply forward it to the user. Here is the old version using Guzzle:
use Symfony\Component\HttpFoundation\StreamedResponse;
public function getMedia($media)
{
try {
$response = $this->client->get('media/' . $media, [
'stream' => true
]
);
$contentType = $response->getHeader('Content-Type');
$body = $response->getBody();
$stream = new StreamedResponse(function () use ($body) {
while (!$body->eof()) {
echo $body->read(1024);
}
});
$stream->headers->set('Content-Type', $contentType);
return $stream;
} catch (ClientException $e) {
return response()->json([
'errors' => json_decode($e->getResponse()->getBody()->getContents())->errors,
'message' => 'Unfortunately we could not find the requested file'
], 404);
}
}
And the new code that I tried to write, without success:
use Symfony\Component\HttpFoundation\StreamedResponse;
public function getMedia($media)
{
$response = Http::withOptions([
'stream' => true
])->get("media/{$media}");
$contentType = $response->header('Content-Type');
$body = $response->body();
$stream = new StreamedResponse(function () use ($body) {
while (!$body->eof()) {
echo $body->read(1024);
}
});
$stream->headers->set('Content-Type', $contentType);
return $stream;
}
Does anyone have any idea how to solve this? I don't know what to do anymore...
I know, 2 years late, but i'm doing something similar, you should access to the response via the psr
instead of:
$body = $response->body(); // This try to return an string
Use this:
$body = $response->toPsrResponse()->getBody(); // the guzzle response
Then you can use your normal code
I hope someone can find this useful,
The following is the controller code that seems to be working through the if statement but the data in the db is not updating.
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($_model = Yii::$app->request->post() && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
I suspect the problem lies in something to do with the fact that it is part of a CRUD code for of users and the form only updates a handful of fields (excluding password, authKey, etc).
Please help.
Thanks
Change your code from
if ($_model = Yii::$app->request->post() && $model->save()) {
to :
if ($model->load(Yii::$app->request->post()) && $model->save()) {