I have this managing institution project. Each institution has its own DB like 'institution_1', 'institution_2' etc. I'm creating that institution DB and trying to migrate into them after I created them. Because it takes to long to migrate (I think bc it has a lot of tables) I'm using queue and jobs. Job is running but not the migration!!
*Controller: *
$newDb = DB::connection('rc')->statement("CREATE DATABASE intitution_$institutionId CHARACTER SET utf8 COLLATE utf8_general_ci;");
DB::connection('rc')->statement("GRANT ALL PRIVILEGES ON `institution\\_$institutionId`.* TO 'institutions'#'%' WITH GRANT OPTION");
if ($newDb) {
Config::set('database.connections.th', [
'driver' => 'mysql',
'host' => 'localhost',
'port' => '3306',
'database' => 'institution_'.$institutionId,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'timezone' => '+00:00',
'strict' => false,
]);
$job = (new CreateInstitutionDb())->delay(Carbon::now()->addSecond(120));
dispatch($job);
return true;
}
*CreateInstitutionDb Job: *
public function handle()
{
\Illuminate\Support\Facades\Artisan::call('migrate',['--database' => 'th', '--force' => true]);
}
You're delaying the job execution by a 2 minutes, I assume you want to set 2 minutes timeout
$job = new CreateInstitutionDb();
And in your job
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class CreateInstitutionDb implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* The number of seconds the job can run before timing out.
*
* #var int
*/
public $timeout = 120;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
\Illuminate\Support\Facades\Artisan::call('migrate', ['--database' => 'th', '--force' => true]);
}
}
Related
I am trying to implement a queue to send email in laravel. My .env file
MAIL_DRIVER = smtp
MAIL_HOST = smtp.gmail.com
MAIL_PORT = 587
MAIL_FROM_ADDRESS = from#gmail.com
MAIL_USERNAME = from
MAIL_PASSWORD = ********
MAIL_ENCRYPTION = tls
QUEUE_CONNECTION=database
My config/queue.php
'connections' => [
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
'after_commit' => false,
],
]
config/mail.php
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN'),
],
]
My Job file
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;
class SendSampleMail implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
Mail::send(['text' => 'mail'], ['name' => 'TestUser'], function ($message) {
$message->to('to#mailinator.com', 'testUserName')->subject('Test Laravel email');
$message->from('from#gmail.com', 'Test Mail');
});
}
}
In the controller, I am calling it like
$job = new SendSampleMail();
$this->dispatch($job);
The mail.blade.php
<p>Sending Mail from Laravel.</p>
When I run
php artisan queue:work
The jobs are queued but email fails to be sent.
I need to fix that issue. Any help would be appreciated. Thanks in advance.
As per the laravel document, create the jobs table in the database.
Run the below two command for the creating the table
php artisan queue:table
php artisan migrate
I need to fetch the SMTP data in the account of user that will be saved in the database. That way it couldn't pull the data from the .env file.
I'm using Laravel 8
For example, instead of looking for SMTP authentication in .env I would look in the database:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mail;
use Config;
use App\Mail\EmailManager;
class NewsletterController extends Controller
{
public function testEmail(Request $request){
$array['view'] = 'emails.newsletter';
$array['subject'] = "SMTP Test";
$array['from'] = 'email#email.com';
$array['content'] = "This is a test email.";
Config::set('mail.host', 'smtp.mailtrap.io');
Config::set('mail.username', 'email#email.com');
Config::set('mail.password', 'd13ea2a29a5cee');
Config::set('mail.port', 587);
try {
Mail::to($request->email)->send(new EmailManager($array));
} catch (\Exception $e) {
dd($e);
}
flash(translate('An email has been sent.'))->success();
return back();
}
}
I solved.
I Created a file with configutations:
/app/Providers/MailConfigServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
use App\Models\EmailSetting;
use Config;
class MailConfigServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
if (\Schema::hasTable('email_settings')) {
$mail = DB::table('email_settings')->first();
if ($mail) //checking if table is not empty
{
$config = array(
'driver' => $mail->driver,
'host' => $mail->host,
'port' => $mail->port,
'from' => $mail->from,
'encryption' => $mail->encryption,
'username' => $mail->username,
'password' => $mail->password,
'sendmail' => '/usr/sbin/sendmail -bs',
'pretend' => false,
);
Config::set('mail', $config);
}
}
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
}
}
And added this line on app/config
App\Providers\MailConfigServiceProvider::class
I am consuming and external API using Guzzle. The I want to save into the database on my localhost before I eventually move it to the server.
Localhost:8888/myapp
It works on Postman and I could see the data when I used dd();
Console\Commands\UpdateCreateEmployee
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Employee;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
class UpdateCreateEmployee extends Command
{
protected $signature = 'command:UpdateCreateEmployee';
protected $description = 'Update or Create Employee Profile';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$userCompany = Auth::user()->company_id;
$client = new Client();
$res = $client->request('GET','https://api.apptest.net/staff', [
'query' => ['key' => 'wwwwwwdddd']
])->getBody();
$clientdatas = json_decode($res->getContents(), true);
foreach($clientdatas as $clientdata)
{
$employee = HrEmployee::updateOrCreate([
'employee_code' => $clientdata->staff_id,
],
[
'username' => strtok($request->email_company, '#'),
'first_name' => $clientdata->first_name,
'last_name' => $clientdata->flast_name,
'other_name' => $clientdata->middle_name,
'date_of_birth' => Carbon::parse($clientdata['date_of_birth'])->toDateString(),
'hr_status' => $clientdata->hr_status,
'address' => $clientdata->address,
'company_id' => 1,
'country_name' => $clientdata->country,
'email' => $clientdata->email,
]);
//user
$user = User::updateOrCreate([
'email' => $employee->email,
],
[
'username' => $employee->username,
'password' => bcrypt("123456"),
'first_name' => $employee->first_name,
'last_name' => $employee->last_name,
]);
$user->assignRole('Employee');
$employee->update(['user_id' => $user->id]);
}
}
}
kernel
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
'App\Console\Commands\UpdateCreateEmployee',
];
protected function schedule(Schedule $schedule)
{
$schedule->command('command:UpdateCreateEmployee')
->everyFifteenMinutes();
}
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
After fifteen minutes, I checked the database, there was nothing there.
How do I make it work on my localhost windows?
Thanks
The native way to use cron jobs under Windows environment is Task Scheduler.
Make a new task to run every minute:
Program script: path/to/your/php.exe
Add arguments: path/to/your/artisan schedule:run
More information can be found here: https://quantizd.com/how-to-use-laravel-task-scheduler-on-windows-10/
i'm connect multiple Database and i use Laravel Excel I can'n export. This is error "Database [mysql] not configured."
i'm use laravel 6.0 and phpmyadmin version 4.4.15.10
controller
public function exportExcel()
{
return Excel::download(new merakiExport, 'MerakiBluetooth.xlsx');
}
app/Exports
namespace App\Exports;
use App\MerakiBluetoothTemp;
use Maatwebsite\Excel\Concerns\FromCollection;
class merakiExport implements FromCollection
{
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return MerakiBluetoothTemp::all();
}
}
config/database
'meraki' => [
'driver' => 'mysql',
'host' => env('DB_HOST5', ''),
'port' => env('DB_PORT5', ''),
'database' => env('DB_DATABASE5', 'forge'),
'username' => env('DB_USERNAME5', 'forge'),
'password' => env('DB_PASSWORD5', ''),
'unix_socket' => env('DB_SOCKET5', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
env
DB_HOST5=sql.laravel.com
DB_PORT5=3306
DB_DATABASE5=time_sheet
DB_USERNAME5=*****
DB_PASSWORD5=*****
I succeeded too.
app/Exports
namespace App\Exports;
use App\MerakiBluetoothTemp;
use Maatwebsite\Excel\Concerns\FromCollection;
use App\Http\Controllers\Controller;
class merakiExport extends Controller implements FromCollection
{
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return MerakiBluetoothTemp::all();
}
}
I have setup laravel and used it's default authentication controller but I modified the table name and it's table structure and accordingly I also changed the RegisterController and LoginController. And the RegisterController is working fine and registering a new user but when ever I try to login using the login form it gives the same validation error of "These credentials do not match our records."
I have attached the following files: LoginController, RegisterController, Admin(Model), Config->auth
I have overridden the username field according to my EmailAddress field.
Admin Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
class admin extends Authenticatable
{
use Notifiable;
public $table = 'admin';
public $timestamps = false;
protected $primaryKey = 'AdminId';
protected $fillable = ['FirstName', 'LastName', 'FirstName_ar','LastName_ar','EmailAddress','Password','IsActive','remember_token'];
protected $hidden = ['Password', 'remember_token'];
public function getAuthPassword()
{
return $this->Password;
}
}
Login Controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Auth;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function username()
{
return 'EmailAddress';
}
public function getRememberTokenName()
{
return "remember_token";
}
}
Register Controller
<?php
namespace App\Http\Controllers\Auth;
use App\admin;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'firstname' => 'required|string|max:255',
'lastname' => 'required|string|max:255',
'firstname_ar' => 'required|string|max:255',
'lastname_ar' => 'required|string|max:255',
'email' => 'required|string|email|max:255',
'password' => 'required|string|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return admin::create([
'FirstName' => $data['firstname'],
'LastName' => $data['lastname'],
'FirstName_ar' => $data['firstname_ar'],
'LastName_ar' => $data['lastname_ar'],
'EmailAddress' => $data['email'],
'Password' => bcrypt($data['password']),
'IsActive' => 1,
'remember_token' => str_random(10)
]);
}
public function getRememberTokenName()
{
return $this->remember_token;
}
}
Config->auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'admin',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'admin',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
// 'users' => [
// 'driver' => 'eloquent',
// 'model' => App\User::class,
// ],
'admin' => [
'driver' => 'eloquent',
'model' => App\admin::class,
],
],
'passwords' => [
// 'users' => [
// 'provider' => 'users',
// 'table' => 'password_resets',
// 'expire' => 60,
// ],
'admin' => [
'provider' => 'admin',
'table' => 'password_resets',
'expire' => 60,
],
],
];
In the RegisterController, in the create method, instead of
'password' => bcrypt($data['password']), do this
'password' => Hash::make($data['password'])
Probably why your error is happening because maybe when you're registering you're using the bcrypt hashing method for the password but when you're logging, it's using a different hashing method.
Make sure to import the class
use Illuminate\Support\Facades\Hash;
at the top of your RegisterController file.
One more thing to take care of here is to make sure when you're inserting the new user record in the database, make sure to lowercase the email by default and when logging, make sure to lowercase the email too. Some databases are case sensitive by default. So you may have a problem there.
Like you have an email in the database,
Admin#example.com and when logging, you give admin#example.com, it will not match in that case.
Hope this helps.