Spatie Laravel-multitenancy run migrate command after tenant create error - multi-tenant

I am using Spatie Laravel-multitenancy . With the following code i am creating a new tenant, then a database and after that using the artisan command provied by the package to migrate the particular tenant database. Everything is working fine . Tenant , database even migration has been done . But after that it shows error as below.
Mycode
try {
if ($this->isTenantExists($this->domain)) {
throw new Exception("Error Processing Request", 1);
}
$tenant = Tenant::create([
'name' => $this->name,
'domain' => $this->domain,
'database' => $this->database,
]);
if ($this->isDatabaseExists($this->database)) {
throw new Exception("Error Processing Request", 1);
}
$charset = config("database.connections.mysql.charset", 'utf8mb4');
$collation = config("database.connections.mysql.collation", 'utf8mb4_unicode_ci');
config(["database.connections.mysql.database" => null]);
$query = "CREATE DATABASE IF NOT EXISTS $this->database CHARACTER SET $charset COLLATE $collation;";
DB::statement($query);
Artisan::call("tenants:artisan migrate --tenant={$tenant->id}");
} catch (\Throwable $th) {
Log::error($th);
}

It was a session_driver issue. It works when i changed session driver to file on env file.

Related

DB Transaction not rolling back [Laravel 7.3]

I'm running Laravel 7.3 on an app, and I feel like this is potentially a Laravel framework bug because I'm racking my brain on this...
I've got a DB Transaction with model saves within it, all within a try/catch but it's still saving the model updates, and I just can't see why because it hits the catch() and the response json hits, so I assume the rollback is running, yet the database is still updating.
try {
DB::beginTransaction();
foreach ($models as $model) {
$model->rungroup_id = $rungroup->id;
$model->zone_id = $rungroup->getFirstZoneID();
$model->delivery_status = 'next';
$model->save();
}
DB::commit();
return response()->json(['status' => 'success']);
} catch (Throwable | Exception $e) {
DB::rollBack();
Log::error($e);
return response()->json([
'status' => 'error',
'message' => $e->getMessage(),
], 500);
}
Any ideas?
After updating Laravel and many other attempts at rewriting the code to see if I made a silly mistake, I ended up finding that the person who created the database tables set the Table engine to MyISAM rather than InnoDB which is required for the DB transactions... I wish Laravel threw an error so I would've known, but this has definitely saved my sanity, and hope it helps others.

Lumen job dispatching done without database Queue Driver

What do I have:
Lumen service which processing particular Job
Laravel portal which sending file to that service for processing by it
Once it was using only JS and Ajax it worked almost fine - the only what I had to implement is CORS middleware. However after I moved logic to JWT (using jwt-auth package) and GuzzleHttp (I'm using it to send requests to service API) Job stopped processing throught database queue instead it running as if Queue driver being set to sync.
Following is controller which I'm calling during API call:
public function processPackageById(Request $request) {
$id = $request->package_id;
$package = FilePackage::where('id', '=', $id)->where('package_status_id', '=', 1)->first();
if($package) {
Queue::push(new PackageProcessingJob(
$this->firm,
$this->accounts,
$package
));
return 'dispatching done for ' . $id;
}
return 'dispatching not done for ' . $id;
}
where $this->firm and $this->accounts are injected Repositories for particular models. FilePackage object being created on Laravel site and both shares same database to work with.
As result no job being incerted into jobs table. When I use Postman everything is fine. However when I'm trying to send request from Laravel backend:
public function uploaderPost(Request $request)
{
// Here we get auth token and put into protected valiable `$this->token`
$this->authorizeApi();
$requestData = $request->except('_token');
$package = $requestData['file'];
$uploadPackageRequest =
$this->client->request('POST', config('bulk_api.url') .'/api/bulk/upload?token=' . $this->token,
[
'multipart' => [
[
'name' => 'file',
'contents' => fopen($package->getPathName(), 'r'),
'filename' => $package->getClientOriginalName(),
],
]
]);
$uploadPackageRequestJson = json_decode($uploadPackageRequest->getBody()->getContents());
$uploadPackageRequestStatus = $uploadPackageRequestJson->status;
if($uploadPackageRequestStatus == 1) {
$package = BulkUploadPackage::where('id', '=',$uploadPackageRequestJson->id)->first();
// If package is okay - running it
if($package !== null){
// Here where I expect job to be dispatched (code above)
$runPackageRequest =
$this->client->request('POST', config('api.url') .'/api/bulk/run?token=' . $this->token,
[
'multipart' => [
[
'name' => 'package_id',
'contents' => $package->id
],
]
]);
// Here I'm receiving stream for some reason
dd($runPackageRequest->getBody());
if($runPackageRequest->getStatusCode()==200){
return redirect(url('/success'));
}
}
}
return back();
}
Could anyone advise me what is wrong here and what causes the issue?
Thank you!
Alright, it was really interesting. After echoing config('queue.default') in my contoller it appeared that it's value indeed sync nevertheless that I set everything correctly.
Then I assumed that maybe the reason in Laravel itself and its variables. Indeed in .env file from Laravel side QUEUE_DRIVER being set to sync. After I changed it to QUEUE_DRIVER=database everything started working as expected.
Hope that will help someone in future.

Disable Query_Log() before executing some queries in Laravel

I am developing web base application using Laravel 5.6 . There are many database queries to execute.
As a security purpose I try to store my all queries into a database table as Query log. I have uses AppServiceProvider service provider to do that. Now I want to disable Query_Log() function for a while that prevent storing particular database query also.
when I run app with above code, It was running while exceeding database maximum execution time.
Can somebody suggest me how I do that?
public function boot()
{
if(env('App_Debug')){
DB::listen(function($query){
//DB::connection()->disableQueryLog();
Query_Log::insert([
'query_string'=>$query->sql,
'user' => "Admin",
'created_at' =>Carbon::now()->toDateTimeString(),
]);
});
}
}
This is how i exclude the listener. i don't know if there is existing function
DB::listen(function ($query) {
try {
//check if the query log is the excluded table
if (preg_match('(query_activities)', $query->sql) == 0) {
QueryActivity::query()->create([
'connection_name' => $query->connectionName,
'time_taken' => $query->time,
'query' => $query->query,
'bindings' => Utils::aesEncrypt(json_encode($query->bindings)),
]);
}
} catch (\Exception $exception) {
}
});

Laravel 5 mobile app login via token authentication

Is there any library or tutorial on token authentication compatible for Laravel 5? I'm working on a client mobile application and as far as I know, login is usually made via token auth, but surprisingly there are absolutely no results on the subject. Thanks in advance
$fb = new Facebook\Facebook([
'app_id' => config('services.facebook.app_id'),
'app_secret' => config('services.facebook.app_secret'),
'default_graph_version' => config('services.facebook.api_version'),
]);
try {
$response = $fb->get('/me?fields=id,name,email,gender', $request->input('facebook_access_token'));
} catch (Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
//echo 'Graph returned an error: ' . $e->getMessage();
//exit;
return $this->setStatusCode(403)->respondWithError('Not Authorized!');
} catch (Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
//echo 'Facebook SDK returned an error: ' . $e->getMessage();
//exit;
return $this->setStatusCode(500)->respondWithError('Backend Error!');
}
$facebookUser = $response->getGraphUser();

Laravel 4 user login authentication

i'm using laravel with oracle database. Now, i'm making login sections. When i was input correct username and password, result is okay. But i was input incorrect username or password, following exception occured:
Illuminate \ Database \ QueryException
oci_error() expects parameter 1 to be resource, object given (SQL: select * from test_laravel_auth where username = tugsuu and password = testsss)
My controller code:
$user = DB::table('test_laravel_auth')->where('username', '=', $input['login_username'])
->where('password', '=', $input['login_password'])
->get();
return count($user);
if($user != null){
return "SUCCESS :D";
}
return "failed";
I assume you were using [jfelder/Laravel-OracleDB] package. It is a known issue as stated on site and a fixed was already added. Try updating your packages by running composer update.
Another option is to use yajra/laravel-oci8 package to connect to Oracle.
try this
$user = DB::table('test_laravel_auth')->where('username', '=', Input::get('username'))
->where('password', '=', Input::get('password'))
->get();
if(Auth::attempt($user))
{
//here success
}
else
{
return Redirect::to('login')->with('login_errors','Invalid Login Credentials.');
}
I suggest you use first instead of get(), this will retrieve the first record (only one should be found). You could also try with firstOrFail() and create an error handler if it "fails". If it fails = login incorrect.
$user = DB::table('test_laravel_auth')->where('username', '=', Input::get('login_username'))->where('password', '=', Input::get('login_password'))->first();
if (!is_null($user))
{
Auth::login($user);
}
else
{
//failed
}
Im also using Oracle database in Laravel and this solution works for me:
if ( Auth::attempt( array( 'user_name' => Input::get( 'username' ), 'password' => Input::get( 'password' ) ) ) )
{
return Redirect::intended( 'dashboard' );
}
else
{
return Redirect::to( 'login' )->withInput( Input::except( 'password' ) );
}
My code is just same on the Laravel documentation. It doesn't require you to use queries for authentication, all you need to use is the authentication class that comes with Laravel.
What driver/package you are using? Im using the yajra/laravel-oci8 package to make Oracle work with Laravel.
You may read more about laravel-oci8 package documentation on its page: https://github.com/yajra/laravel-oci8

Resources