I am scraping a site a get some of the data and it's a time taking job so I googled and found that Queue is good for this process I am stucked in this error
Serialization of 'Closure' is not allowed
My code:
class SiteScraper extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $client;
protected $crawler;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct()
{
$this->client = new Client();
$this->crawler = $this->client->request('GET', 'example.com/login/');
$form = $this->crawler->selectButton('Log In')->form();
$this->crawler = $this->client->submit($form, array('email' => 'useremail', 'pass' => 'pass'));
$this->crawler->filter('.flash-error')->each(function ($node) {
print $node->text() . "\n";
});
}
public function handle()
{
$crawler = $this->client->request('GET', $url_to_traverse);
$status_code = $this->client->getResponse()->getStatus();
if($status_code == 200){
$crawler->filter('.friendBrowserNameTitle > a')->each(function ($node) {
$names = $node->text() . '<br>';
$profileurl = $node->attr('href') . '<br>';
echo "Name : " . $names . " Profile Link : " . $profileurl;
});
}
else{
echo $status_code;
}
}
}
Any help where I am going wrong?
Only Eloquent models will be gracefully serialized and unserialized when the job is processing (Source)
So I guess that in your case, you have to write your current construct code into handle() method
class SiteScraper extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct(){ }
public function handle()
{
$client = new Client();
$crawler = $client->request('GET', 'example.com/login/');
$form = $crawler->selectButton('Log In')->form();
$crawler = $client->submit($form, array('email' => 'useremail', 'pass' => 'pass'));
$crawler->filter('.flash-error')->each(function ($node) {
print $node->text() . "\n";
});
$crawler = $client->request('GET', $url_to_traverse);
$status_code = $client->getResponse()->getStatus();
if($status_code == 200){
$crawler->filter('.friendBrowserNameTitle > a')->each(function ($node) {
$names = $node->text() . '<br>';
$profileurl = $node->attr('href') . '<br>';
echo "Name : " . $names . " Profile Link : " . $profileurl;
});
}
else{
echo $status_code;
}
}
}
Related
I want to output user activity history.
Here's observer that i want to output message of user activity to my front end if($drop_student){ Logger::createLog("Student Schedule Removed for ". $student->first_name . " " . $student->last_name . " '" . $schedule->name . "'");
UPDATED
public function created(StudentSchedule $student_schedule)
{
$student = $student_schedule->student()->get()->first();
$schedule = $student_schedule->schedule()->get()->first()->subject->subject;
Logger::createLog("Student Schedule Added for " . $student->first_name . " " . $student->last_name . " '" . $schedule->name . "'");
}
/**
* Handle the student schedule "updated" event.
*
* #param \App\Models\Student\Schedule $student_schedule
* #return void
*/
public function updated(StudentSchedule $student_schedule)
{
$student = $student_schedule->student()->get()->first();
$schedule = $student_schedule->schedule()->get()->first()->subject->subject;
$drop_students = $student_schedule->schedule()->where('id')->get();
foreach ($drop_students as $drop_student) {
$drop_student = $student_schedule->schedule();
}
$drop_student->save(['final_grade' => 'DRP']);
if ($drop_student) {
Logger::createLog("Student Schedule Removed for " . $student->first_name . " " . $student->last_name . " '" . $schedule->name . "'");
} else {
Logger::createLog("Student Schedule Updated for " . $student->first_name . " " . $student->last_name . " '" . $schedule->name . "'");
}
}
Here my relationship models
student & schedule hasMany student schedule
student schedule model:
class Schedule extends Model
{
use HasFactory;
protected $table = 'student.schedules';
protected $fillable = [
'student_id',
'schedule_id',
'removal_grade',
'final_grade',
'is_published',
];
public $timestamps = false;
public function student()
{
return $this->belongsTo('App\Models\Student', 'student_id');
}
public function schedule()
{
return $this->belongsTo('App\Models\Schedule', 'schedule_id');
}
}
student model:
class Student extends Model
{
use HasFactory;
const MALE = 'male';
const FEMALE = 'female';
protected $table = 'students';
protected $fillable = [
'first_name',
'last_name',
'middle_name',
'suffix',
'email',
'student_number',
'sex',
'birthdate',
'lrn',
"profile_picture"
];
protected $appends = ['allow_delete'];
public function schedules()
{
return $this->hasMany('App\Models\Student\Schedule', 'student_id', 'id');
}
}
schedule model:
class Schedule extends Model
{
use HasFactory;
const MONDAY = 'M';
const TUESDAY = 'T';
const WEDNESDAY = 'W';
const THURSDAY = 'TH';
const FRIDAY = 'F';
const SATURDAY = 'S';
const SUNDAY = 'SUN';
protected $table = 'schedules';
protected $fillable = [
'start_time',
'end_time',
'room_id',
'subject_id',
'session_id',
'user_id',
'day',
'section_id',
'price_per_unit_id',
];
protected $casts = ['day' => 'array'];
protected $appends = ['allow_delete', 'enrollments_count'];
public function students()
{
return $this->hasManyThrough(
'App\Models\Student',
'App\Models\Student\Schedule',
'schedule_id',
'id',
'id',
'student_id',
);
}
public function studentSchedules()
{
return $this->hasMany('App\Models\Student\Schedule', 'schedule_id', 'id');
}
}
Here's api that i use.
Route::post('/drop-schedules', [EnrollmentController::class, 'dropSchedules']);
Here's dropSchedules method in controller.
public function dropSchedules(Request $request)
{
StudentSchedule::whereIn('id', $request->student_schedules)->update(['final_grade' => 'DRP']);
return response()->json([
'message' => 'Student schedules successfully dropped.'
], 200);
}
but when i fire the drop schedule button. This logic it doesn't run. Only the created method Student Schedule Added for
I am trying to dispatch some files to my queue.
The dispatch() function is not working all around my stuff - for Example:
$auth = Auth::user();
$name = $request->file('file')->getClientOriginalName();
just give me a null, when DD($...); ?!
$userid = User::find(1); (by hitting the users id..) works fine!
can someone explain why that dispatch() function is not working for me?
the job code:
`
class File_Upload implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $directory;
protected $uploadDataName;
protected $inputFormName;
protected $request;
public function __construct( $directory, $uploadDataName, $inputFormName )
{
//$this->$request = $request;
$this->directory = $directory;
$this->uploadDataName = $uploadDataName;
$this->inputFormName = $inputFormName;
}
$request, $directory, $uploadDataName, $inputFormName
public function handle()
{
//vars
$request = new Request;
dd($request->file());
$name = $this->request->file($this->inputFormName)->getClientOriginalName(); // 'file' z.B
$validate = Validator::make($this->request->all(),
[
$this->inputFormName => "required|max:1000"
] );
if ( $validate->fails() )
{
return response()->json('file.prop.error'); // JSON response!
}
// get client-data Name
if ($name !== $this->uploadDataName)
{
return response()->json('file.name.error'); // JSON response!
}
$this->request->file($this->inputFormName)->storeAs($this->directory, $name) ;
//event(new Event_Data_Upload_successfull( SupportController::getAuthUser(), $uploadDataName, $directory ) );
}
The Controller...
dispatch( new File_Upload('name', 'name.csv', 'file') );
return redirect('/');
In SYNC mode that code works 100% fine.
ive try to do my first steps with codeignitter, so i have write a new methode(function) in a existing class.
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class App
{
/**
* Options autoload=1
* #var array
*/
private $options = [];
/**
* Quick actions create aside
* #var array
*/
private $quick_actions = [];
/**
* CI Instance
* #deprecated 1.9.8 Use $this->ci instead
* #var object
*/
private $_instance;
/**
* CI Instance
* #var object
*/
private $ci;
/**
* Show or hide setup menu
* #var boolean
*/
private $show_setup_menu = true;
/**
* Available reminders
* #var array
*/
private $available_reminders = ['customer', 'lead', 'estimate', 'invoice', 'proposal', 'expense', 'credit_note'];
/**
* Tables where currency id is used
* #var array
*/
private $tables_with_currency = [];
/**
* Media folder
* #var string
*/
private $media_folder;
/**
* Available languages
* #var array
*/
private $available_languages = [];
public function __construct()
{
$this->ci = & get_instance();
// #deprecated
$this->_instance = $this->ci;
$this->init();
do_action('app_base_after_construct_action');
}
/**
* Check if database upgrade is required
* #param string $v
* #return boolean
*/
public function is_db_upgrade_required($v = '')
{
if (!is_numeric($v)) {
$v = $this->get_current_db_version();
}
$this->ci->load->config('migration');
if ((int) $this->ci->config->item('migration_version') !== (int) $v) {
return true;
}
return false;
}
/**
* Return current database version
* #return string
*/
public function get_current_db_version()
{
$this->ci->db->limit(1);
return $this->ci->db->get('tblmigrations')->row()->version;
}
/**
* Upgrade database
* #return mixed
*/
public function upgrade_database()
{
if (!is_really_writable(APPPATH . 'config/config.php')) {
show_error('/config/config.php file is not writable. You need to change the permissions to 755. This error occurs while trying to update database to latest version.');
die;
}
$update = $this->upgrade_database_silent();
if ($update['success'] == false) {
show_error($update['message']);
} else {
set_alert('success', 'Your database is up to date');
if (is_staff_logged_in()) {
redirect(admin_url(), 'refresh');
} else {
redirect(site_url('authentication/admin'));
}
}
}
/**
* Make request to server to get latest version info
* #return mixed
*/
public function get_update_info()
{
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_USERAGENT => $this->ci->agent->agent_string(),
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_TIMEOUT => 30,
CURLOPT_URL => UPDATE_INFO_URL,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => [
'update_info' => 'true',
'current_version' => $this->get_current_db_version(),
],
]);
$result = curl_exec($curl);
$error = '';
if (!$curl || !$result) {
$error = 'Curl Error - Contact your hosting provider with the following error as reference: Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl);
}
curl_close($curl);
if ($error != '') {
return $error;
}
return $result;
}
/**
* Return all available languages in the application/language folder
* #return array
*/
public function get_available_languages()
{
$languages = $this->available_languages;
return do_action('before_get_languages', $languages);
}
/**
* Function that will parse table data from the tables folder for amin area
* #param string $table table filename
* #param array $params additional params
* #return void
*/
public function get_table_data($table, $params = [])
{
$hook_data = do_action('before_render_table_data', [
'table' => $table,
'params' => $params,
]);
foreach ($hook_data['params'] as $key => $val) {
$$key = $val;
}
$table = $hook_data['table'];
$customFieldsColumns = [];
$path = VIEWPATH . 'admin/tables/' . $table . '.php';
if (file_exists(VIEWPATH . 'admin/tables/my_' . $table . '.php')) {
$path = VIEWPATH . 'admin/tables/my_' . $table . '.php';
}
include_once($path);
echo json_encode($output);
die;
}
/**
* Check if a option value is preset or individual
* #param string $name, string $value
* #return true/false
*/
public function option_is_preset($name,$value)
{
$str="`name`='".$name."' and value='".$value."' ";
$this->ci->db->select('id, name, value');
$this->ci->db->where($str);
$row = $this->ci->db->get('4U_tbloptions_preset')->row_array();
if ($row['id']>0) {
return true;
}
return false;
}
/**
* All available reminders keys for the features
* #return array
*/
public function get_available_reminders_keys()
{
return $this->available_reminders;
}
/**
* Get all db options
* #return array
*/
public function get_options()
{
return $this->options;
}
/**
* Function that gets option based on passed name
* #param string $name
* #return string
*/
public function get_option($name)
{
if ($name == 'number_padding_invoice_and_estimate') {
$name = 'number_padding_prefixes';
}
$val = '';
$name = trim($name);
if (!isset($this->options[$name])) {
// is not auto loaded
$this->ci->db->select('value');
$str="`name`='".$name."' and `maccid`='".$this->ci->session->userdata('macc_id')."'";
$this->ci->db->where($str);
$row = $this->ci->db->get('4U_accounts_tbloptions')->row();
if ($row) {
#echo"Wert aus account_tbloptions";
$val = $row->value;
}
} else {
#echo $name.'->'.$val.' Autoload - nicht aus DB!<br>';
$val = $this->options[$name];
}
$hook_data = do_action('get_option', ['name' => $name, 'value' => $val]);
//Fallback auf Standardwert
if ($hook_data['value']=='')
{
$this->ci->db->select('value');
$this->ci->db->where('name', $name);
$row = $this->ci->db->get('4U_tbloptions_preset')->row();
if ($row) {
#echo"Wert aus preset";
$val = $row->value;
}
$hook_data = do_action('get_option', ['name' => $name, 'value' => $val]);
}
return $hook_data['value'];
}
/**
* Add new quick action data
* #param array $item
*/
public function add_quick_actions_link($item = [])
{
$this->quick_actions[] = $item;
}
/**
* Quick actions data set from admin_controller.php
* #return array
*/
public function get_quick_actions_links()
{
$this->quick_actions = do_action('before_build_quick_actions_links', $this->quick_actions);
return $this->quick_actions;
}
/**
* Aside.php will set the menu visibility here based on few conditions
* #param int $total_setup_menu_items total setup menu items shown to the user
*/
public function set_setup_menu_visibility($total_setup_menu_items)
{
$this->show_setup_menu = $total_setup_menu_items == 0 ? false : true;
}
/**
* Check if should the script show the setup menu or not
* #return boolean
*/
public function show_setup_menu()
{
return do_action('show_setup_menu', $this->show_setup_menu);
}
/**
* Return tables that currency id is used
* #return array
*/
public function get_tables_with_currency()
{
return do_action('tables_with_currency', $this->tables_with_currency);
}
/**
* Return the media folder name
* #return string
*/
public function get_media_folder()
{
return do_action('get_media_folder', $this->media_folder);
}
/**
* Upgrade database without throwing any errors
* #return mixed
*/
private function upgrade_database_silent()
{
$this->ci->load->config('migration');
$beforeUpdateVersion = $this->get_current_db_version();
$this->ci->load->library('migration', [
'migration_enabled' => true,
'migration_type' => $this->ci->config->item('migration_type'),
'migration_table' => $this->ci->config->item('migration_table'),
'migration_auto_latest' => $this->ci->config->item('migration_auto_latest'),
'migration_version' => $this->ci->config->item('migration_version'),
'migration_path' => $this->ci->config->item('migration_path'),
]);
if ($this->ci->migration->current() === false) {
return [
'success' => false,
'message' => $this->ci->migration->error_string(),
];
}
update_option('upgraded_from_version', $beforeUpdateVersion);
return [
'success' => true,
];
}
/**
* Init necessary data
*/
protected function init()
{
//Autoloadfelder zuerst alle Presetfelder, die dann mit den Individualfeldern ueberschrieben werden
$optionsA = $this->ci->db->select('name, value')
->where('autoload', 1)
->get('4U_tbloptions_preset')->result_array();
$str=" 'maccid'='".$this->ci->session->userdata('macc_id')."' AND 'autoload'='1' ";
$optionsB = $this->ci->db->select('name, value')
->where($str)
->get('4U_accounts_tbloptions')->result_array();
$options=array_merge($optionsA, $optionsB);
// Loop the options and store them in a array to prevent fetching again and again from database
foreach ($options as $option) {
$this->options[$option['name']] = $option['value'];
}
/**
* Available languages
*/
foreach (list_folders(APPPATH . 'language') as $language) {
if (is_dir(APPPATH . 'language/' . $language)) {
array_push($this->available_languages, $language);
}
}
/**
* Media folder
* #var string
*/
$this->media_folder = do_action('before_set_media_folder', 'media');
/**
* Tables with currency
* #var array
*/
$this->tables_with_currency = [
[
'table' => 'tblinvoices',
'field' => 'currency',
],
[
'table' => 'tblexpenses',
'field' => 'currency',
],
[
'table' => 'tblproposals',
'field' => 'currency',
],
[
'table' => 'tblestimates',
'field' => 'currency',
],
[
'table' => 'tblclients',
'field' => 'default_currency',
],
[
'table' => 'tblcreditnotes',
'field' => 'currency',
],
[
'table' => 'tblsubscriptions',
'field' => 'currency',
],
];
}
/**
* Predefined contact permission
* #deprecated 1.9.8 use get_contact_permissions() instead
* #return array
*/
public function get_contact_permissions()
{
return get_contact_permissions();
}
}
Now i want to use this methode for example like this
echo"Test1: ".get_option('company_logo_dark');
echo"Test2: ".option_is_preset('company_logo_dark');
The methode "get_option" is one of the existing methode in the class.
This (get_option) work, but option_is_present produce a error " Call to undefined function option_is_preset() "
If i try
echo "Test3: ".$this->app->option_is_preset('company_logo',$company_logo);
it will work.
Why the first methode "get_option" i can use in this way ( echo "Test: ".get_option(string); " and why i can't do the same way for the other methode?
Thanks a lot for support me :-)
Inside class, you need to use the pseudo-variable $this
echo"Test1: ". $this->get_option('company_logo_dark');
echo"Test2: ". $this->option_is_preset('company_logo_dark', 'some_value');
Unsing a instance of a class:
$instance = new App();
echo"Test1: ". $instance ->get_option('company_logo_dark');
echo"Test2: ". $instance ->option_is_preset('company_logo_dark', 'some_value');
If the class App is placed in the library directory, you can use the Codeigniter Loader Class
$this->load->library('app');
echo"Test1: ". $this->app->get_option('company_logo_dark');
echo"Test2: ". $this->app->option_is_preset('company_logo_dark', 'some_value');
EDIT 1
get_option method can be called directly only if this is declared outside class. Please see the next example
function method_a($var) {
echo __METHOD__ . ' : ' . $var .'<br />';
}
class MyClass {
public function method_a($var) {
echo __METHOD__ . ' : ' . $var .'<br />';
$this->method_b($var);
}
public function method_b($var) {
echo __METHOD__ . ' : ' . $var .'<br />';
}
}
$instance = new MyClass();
$instance->method_a("Test");
method_a("Test");
this will return:
MyClass::method_a : Test
MyClass::method_b : Test
method_a : Test
EDIT 2
According to the updated class, method option_is_preset takes two arguments, $name and $value and you are trying to call only with one argument
echo"Test2: ".option_is_preset('company_logo_dark'); // wrong
echo"Test2: ".option_is_preset('company_logo_dark', 'some_value'); // correct
In another file i've found that
function get_option($name)
{
$CI = & get_instance();
if (!class_exists('app')) {
$CI->load->library('app');
}
return $CI->app->get_option($name);
}
This explains, why it is possible to call the "get_option" in a normal way of a function.
So i've add
function option_is_preset($name, $value)
{
$CI = & get_instance();
if (!class_exists('app')) {
$CI->load->library('app');
}
return $CI->app->option_is_preset($name, $value);
}
and now i can call the new methode like a function :-))
When i work on locally upload image on folder works perfect but when i try to upload image on amazon web server file not uploaded and back with same page.Is there any problem with my code ?
Here is my controller function to save data :
// CountryController
public function save(Request $request) {
try {
$file = $request->file('flag_image');
$this->validate($request, Country::rules());
//$request->validate(Country::rules());
/*Image Upload code*/
If(Input::hasFile('flag_image')){
$file = Input::file('flag_image');
$destinationPath = public_path(). '/images/admin/country/';
$filename = $file->getClientOriginalName();
$image = time().$filename;
$file->move($destinationPath, $image);
$imgpath = 'images/admin/country/'.$image;
}
if($file !="") {
$request->merge(['flag_image' => $imgpath]);
}
/*Image Upload code end*/
$country = Country::saveOrUpdate($request);
if($file !="") {
$country->flag_image = $imgpath;
$country->save();
}
if($country !== false) {
return redirect()->route('lists-country')->with('success', trans('Country data added successfully.!!'));
} else {
return back()->with('error', "Unable to save country data.!!")->withInput();
}
} catch (\Exception $ex) {
return back()->with('error', "Unable to save country data.!!")->withInput();
}
}
And my model code look like:
//country model
namespace App;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
class Country extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'title',
'short_name',
'flag_image',
'status'
];
const STATUSES = [
'Active' => 'Active',
'Inactive' => 'Inactive',
];
const DEFAULT_STATUS = 'Active';
/**
* Indicates if the model should be timestamped.
*
* #var bool
*/
public $timestamps = false;
public static function rules() {
return [
'title' => 'required|string|max:255',
'short_name' => 'required',
'status' => 'required|string|in:' . implode(",", Country::STATUSES)
];
}
public static function saveOrUpdate(Request $request) {
try {
$id = $request->get('id', false);
$country = false;
DB::transaction(function () use ($request, &$country, $id) {
$country = $id ? Country::findOrFail($id) : new Country();
$country->fill($request->all());
try {
$country->save();
} catch (\Exception $ex) {
throw $ex;
}
});
return $country;
} catch (\Exception $ex) {
throw $ex;
}
} }
What's the problem i didn't find anything.
To get things started, I made a custom Artisan Command called MySqlRestore.
It simply restores the database using the dumped sql file.
Here's my MySqlRestore code:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class MySqlRestore extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'db:restore';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Restores database using info from .env';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$sqlfile = //data from controller;
$ds = DIRECTORY_SEPARATOR;
$host = env('DB_HOST');
$username = env('DB_USERNAME');
$password = env('DB_PASSWORD');
$database = env('DB_DATABASE');
$mysqlpath = 'C:\xampp\mysql\bin\mysql';
$path = 'C:\salesandinventory\Backups\\';
$command = sprintf($mysqlpath . ' --user=' . $username . ' --password=' . $password . ' --host=' . $host . ' ' . $database . ' < ' . $path . $sqlfile);
exec($command);
}
}
Now on this line $sqlfile = //data from controller;, I need the data from my controller.
Here's how my controller looks like:
<?php
namespace App\Http\Controllers;
use App\Database;
use Illuminate\Http\Request;
use Artisan;
class DatabaseController extends Controller
{
public function index()
{
return view('database.index');
}
public function restoreDatabase(Request $request)
{
$sqlfile = $request->sqlfile; // the data I need.
Artisan::call('db:restore');
return view('database.index');
}
}
Now I don't have any idea how to pass $sqlfile = $request->sqlfile; this data from my controller into my Artisan handle function.
Data's are passed through the protected $signature using curly braces {dataName}
e.g
protected $signature = 'db:restore {dataName}'
and it is called using
$this->argument('dataName');
In your controller
Artisan::call('db:restore',['test'=> $test]);
namespace App\Console\Commands;
use Illuminate\Console\Command;
class MySqlRestore extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'db:restore {test}';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Restores database using info from .env';
public $sqlFile;
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$sqlfile = $this->argument('test');
$ds = DIRECTORY_SEPARATOR;
$host = env('DB_HOST');
$username = env('DB_USERNAME');
$password = env('DB_PASSWORD');
$database = env('DB_DATABASE');
$mysqlpath = 'C:\xampp\mysql\bin\mysql';
$path = 'C:\salesandinventory\Backups\\';
$command = sprintf($mysqlpath . ' --user=' . $username . ' --password=' . $password . ' --host=' . $host . ' ' . $database . ' < ' . $path . $sqlfile);
exec($command);
}
}
Call it like this
Artisan::call('db:restore',['test'=> $test]);
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class MySqlRestore extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'db:restore';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Restores database using info from .env';
public $sqlFile;
/**
* Create a new command instance.
*
* #return void
*/
public function __construct($sqlFile)
{
$this->sqlFile = $sqlFile;
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$sqlfile = $this->sqlFile;
$ds = DIRECTORY_SEPARATOR;
$host = env('DB_HOST');
$username = env('DB_USERNAME');
$password = env('DB_PASSWORD');
$database = env('DB_DATABASE');
$mysqlpath = 'C:\xampp\mysql\bin\mysql';
$path = 'C:\salesandinventory\Backups\\';
$command = sprintf($mysqlpath . ' --user=' . $username . ' --password=' . $password . ' --host=' . $host . ' ' . $database . ' < ' . $path . $sqlfile);
exec($command);
}
}
Controller
<?php
namespace App\Http\Controllers;
use App\Database;
use Illuminate\Http\Request;
use Artisan;
class DatabaseController extends Controller
{
public function index()
{
return view('database.index');
}
public function restoreDatabase(Request $request)
{
$sqlfile = $request->sqlfile; // the data I need.
Artisan::call('db:restore',['sqlFile'=>$sqlFile]);
return view('database.index');
}
}
Your controller should not be executing Artisan commands, especially potentially long-running ones like executing a database back-up.
Instead, consider dispatching a queued job that performs the restore. You can then return control to the user and they can get on with things they need to do, instead of keeping a web page open that could possibly timeout and leave the database in a corrupt state.
class DatabaseRestoreController extends Controller
{
public function store(Request $request)
{
dispatch(new RestoreDatabaseJob($request->input('filename')));
return redirect()->back()->withSuccess('Restoring database.');
}
}
And the job class itself:
class RestoreDatabaseJob implements ShouldQueue
{
use InteractsWithQueue;
public $filename;
public function __construct($filename)
{
$this->filename = $filename;
}
public function handle()
{
Artisan::call('db:restore', [
'filename' => $this->filename,
]);
// You can notify user restore completed
// Send email, SMS via notification etc.
}
}