Laravel migration and accessing database error [duplicate] - mysql

This question already has answers here:
Database doesn't exist with laravel
(2 answers)
Closed 9 years ago.
Can't figure out the problem with the database migration or accessing the right database. There exist the users database with data but for some reason I can't access it when I use laravel framework. Please take a look at the error and what I am doing. Thank you.
Error:
Exception
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'database.users' doesn't exist (SQL:
select * from `users`) (Bindings: array ( ))
Database.php:
<?php
return array(
/*
|--------------------------------------------------------------------------
| PDO Fetch Style
|--------------------------------------------------------------------------
|
| By default, database results will be returned as instances of the PHP
| stdClass object; however, you may desire to retrieve records in an
| array format for simplicity. Here you can tweak the fetch style.
|
*/
'fetch' => PDO::FETCH_CLASS,
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => 'mysql',
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => array(
'sqlite' => array(
'driver' => 'sqlite',
'database' => __DIR__.'/../database/production.sqlite',
'prefix' => '',
),
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
'pgsql' => array(
'driver' => 'pgsql',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
),
'sqlsrv' => array(
'driver' => 'sqlsrv',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => '',
'prefix' => '',
),
),
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk have not actually be run in the databases.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => array(
'cluster' => true,
'default' => array(
'host' => '127.0.0.1',
'port' => 6379,
'database' => 0,
),
),
);
Users.php file:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
routes.php file:
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::get('/', function()
{
return View::make('hello');
});
Route::get('/users', function()
{
$users = User::all();
return View::make('users')->with('users' , $users);
});
layout.blade.php:
<html>
<body>
<h1>Laravel Quickstart</h1>
#yield('content')
</body>
</html>
users.php file:
#extends('layout')
#section('content')
#foreach($users as $user)
<p>{{ $user->name}}</p>
#endforeach
#stop
2013_07_02_170745_create_users_table file(migration):
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
public function up()
{
Schema::create('users', function($table)
{
$table->increments('id');
$table->string('email')->unique();
$table->string('name');
$table->timestamps();
});
}
public function down()
{
Schema::drop('users');
}
}

in database.php:
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database', // <--- Change THIS to your DB name
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),

Related

Migration of tables to database

screenshot of Error i am getting>Illuminate\Database\QueryException SQLSTATE[HY000] [1049] Unknown database 'hiring' (SQL: insert into hirings (name, email, subject, message, updated_at, created_at) values (, , , , 2018-01-24 19:31:19, 2018-01-24 19:31:19))
Portfolio is my database name
In .env file is the same, my model name is hiring, my table name is create_hiring_table everything looks fine to me. Anything I am missing?
.env
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:9ALfdXT6SdgOkZ3gFVCExTFY4z/8yzOfbuCuB7dA1h0=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=portfolio
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
my model name hiring.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
class hiring extends Model
{
use Notifiable;
protected $fillable = [
'name','email','subject','message'
];
protected $hidden = [
'password', 'remember_token',
];
}
my controller named mainController
<?php
namespace App\Http\Controllers;
use App\hiring;
use Illuminate\Http\Request;
class mainController extends Controller
{
public function index(){
return view('main.main');
}
public function store(Request $request){
$hiring = new hiring;
$hiring-> name = $request->name;
$hiring-> email = $request->email;
$hiring-> subject = $request->subject;
$hiring-> message = $request->message;
$hiring-> save();
return view('main.main');
}
}
My table is following named create_hiring_table
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateHiringsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('hiring', function (Blueprint $table){
$table->increments('id');
$table->timestamps();
$table->string('name');
$table->string('email');
$table->string('subject');
$table->string('message');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('hiring');
}
}
This is config/databse.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => env('DB_CONNECTION', 'mysql'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
],
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
'sslmode' => 'prefer',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
'client' => 'predis',
'default' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
],
],
];
just add protected $table = 'hiring';
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
class hiring extends Model
{
use Notifiable;
protected $table = 'hiring';
protected $fillable = [
'name','email','subject','message'
];
protected $hidden = [
'password', 'remember_token',
];
}
i found the mistake ever in web.php the rout should be Route::post('/main', 'mainController#store'); instead of Route::get('/main', 'mainController#store');

How i can force an yii2 module to use a specific connection for all his models?

on a module I have add a component named db where i put, like the main Yii component, the data for database connection, I need in my module use everytime the db specified in his configuration for all models and not the main database connection, how I can do this?
You have several way eg. using a separated configuration in app/config/main.php
eg adding a specific dbMyMod to component config
return [
// ...
'components' => [
// ...
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=example',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
'dbMyMod ' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=hostForMudle;dbname=module_db_name',
'username' => 'user_module_name',
'password' => 'password',
'charset' => 'utf8',
],
],
or one way that not require a static configuration in app/confing
could be based on a module function that return a proper db connection
public function myModuleDbCon()
{
$myDbCon = new yii\db\Connection([
'dsn' => 'mysql:host=localhost;dbname=example',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
]);
return myDbConn;
}
then in you module you can retrive the module db connection
aDbConn = Yii::$app->getModule('my_module_name')->myModuleClass->myModuleDbCon();
.
$command = $aDbConn->createCommand('SELECT * FROM myTable');
$result= $command->queryAll();

Laravel Dynamic model database

I have a Model for DB tables, basically is one table but in different databases,
How can I set a connection to DB in Model?
protected $connection = 'ls';
Above code is not that I am looking for, I need to pass host, port, username and password. because conection are stored in DB not in config file.
I was thinking for function __construct() and call like Model($data)::where()..etc
Or I am thinking wrong way, can somebody give me an better idea.?
You can connect from Eloquent model by maintaining following aspects
First you can define multiple connection in database.php file
<?php
return array(
'default' => 'mysql',
'connections' => array(
# Our primary database connection
'mysql' => array(
'driver' => 'mysql',
'host' => 'host1',
'database' => 'database1',
'username' => 'user1',
'password' => 'pass1'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
# Our secondary database connection
'mysql2' => array(
'driver' => 'mysql',
'host' => 'host2',
'database' => 'database2',
'username' => 'user2',
'password' => 'pass2'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
),
);
You have your default connection still set to mysql . This means that, unless we specify otherwise, the application will use that mysql connection.
Now in your model you can specify which connection to use
<?php
class SomeModel extends Eloquent {
protected $connection = 'mysql2';
}
You can also define the connection at runtime via the setConnection method.
<?php
class SomeController extends BaseController {
public function someMethod()
{
$someModel = new SomeModel;
$someModel->setConnection('mysql2');
$something = $someModel->find(1);
return $something;
}
}

Handling DB connection errors in Cakephp

Currently I am using dynamic database switching in Cakephp from the database config file. I am switching based on the subdomain ie: TEST.mysite.com and PROD.mysite.com.
How and where is the best place to test and redirect if there is a database connection?
Thanks,
kSeudo
The quick and dirty way to do this is to put a condition in the constructor. I say dirty because it creates a conditional config and with the introduction of a bug could leave your production app connected to a dev database.
class DATABASE_CONFIG {
public $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => '',
'login' => '',
'password' => '',
'database' => '',
'prefix' => '',
'encoding' => 'utf8'
);
public $testDB = array(
'driver' => 'mysql',
'persistent' => false,
'host' => '',
'login' => '',
'password' => '',
'database' => '',
'prefix' => '',
'encoding' => 'utf8'
);
public function __construct()
{
if (false !== stripos($_SERVER['HTTP_HOST'], 'test'))
{ // Use the test DB since 'test' is present in the server host
$this->default = $testDB;
}
}
}
To test connection you could put the following in the contructor for app_model.php
public function __construct()
{
parent::__construct();
$db =& ConnectionManager::getDataSource('default');
if (empty($db->connection))
{
echo 'oh noes we werent able to connect';
exit;
}
}

two databases in one controller cakePHP

I'm having trouble creating a page, which requires two different databases..
The controller is automaticly set to 'DB2', which is also specified in the database config file.
When i add a var $uses = array ('groups') to the controller, which is from the other DB (DB1), i get the data from only DB2 and all requests to DB1 become a invalid query..
u guys know a solution?
Thanks in advance!
Regards,
Swen
If have multiple datasources defined in your config/database.php file, you should be able to tell your Group model to use the second (non-default) config:
public $useDbConfig = 'db2';
Your config/database.php file should looks something like this:
class DATABASE_CONFIG {
var $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'your_host',
'login' => 'your_login_1',
'password' => 'your_password_1',
'database' => 'DB1',
'prefix' => ''
);
var $db2 = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'your_host',
'login' => 'your_login_2',
'password' => 'your_password_2',
'database' => 'DB2',
'prefix' => ''
);
}