I'm using 2 databases in my Laravel application. I have an SQLite DB which is local and a remote MySQL DB. Right now I need to switch env files to connect to each DB when I need to. My question is, is it possible to switch env files so the models which I'm using for both of the DB work on the corresponding DB.
This project is fairly new so if anyone knows a better way to handle this I'm all ears.
You may define several connections on your config/database.php file and access each connection via the connection method on the DB facade:
$sqliteUsers = DB::connection('sqlite')->select(...);
$mysqlUsers = DB::connection('mysql')->select(...);
Check "Using Multiple Database Connections" Section on Laravel docs for more info.
You may use on method on eloquent models:
use App\User;
$sqliteUsers = User::on('sqlite')->get()
$mysqlUsers = User::on('mysql')->get();
You may also specify a connection for an eloquent model statically:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The connection name for the model.
*
* #var string
*/
protected $connection = 'sqlite';
}
Check "Database Connection" Section on Laravel docs for more info.
Related
Laravel Version: #.#.# 8.18.1
PHP Version: #.#.# 7.4
Database Driver & Version: MySQL 5.7.32
Description:
Had two models (menu, service) with two different databases, connection set in model. when I get menu model with (service) relation, it's working fine. But when used has(service) to get the menu which have service will shown
Base table or view not found: 1146 Table 'common.services' doesn't exist
it will look in my first database
common is my first database name and services are store in second database.
Steps to Reproduce:
create two model in different database
fetch menu with relation has(service) to get only menu which have service
Documentation
From Laravel Documentation :
Eloquent does not currently support querying for relationship
existence across databases. The relationships must exist within the
same database.
QueryBuilder VS Eloquent
What Cause success retrieve on with() and failure on has() ?
QueryBuilder crosses Databases
with() has been implemented in Illuminate\Database\Eloquent\Builder and collects relations in $eagerLoading array to load with query.
Relation has not implement cross Database Feature
but has() is in Illuminate\Database\Eloquent\Concerns\QueriesRelationships trait and adopted in Illuminate\Database\Eloquent\Relations\Relation calls getRelationWithoutConstraints() which is :
/**
* Get the "has relation" base query instance.
*
* #param string $relation
* #return \Illuminate\Database\Eloquent\Relations\Relation
*/
protected function getRelationWithoutConstraints($relation)
{
return Relation::noConstraints(function () use ($relation) {
return $this->getModel()->{$relation}();
});
}
as PHPDoc says, its just getting base query instance for has relation .
its a simple method JUST creating a simple Base Query based on getModel() query (parent query) and add it.
The solution can be achieve using DB::raw.
I am very new to Laravel and quite confuse with the model and database thing. I understand that a model represent one table. So I created a model using artisan command without migration and it created the code as follow.
namespace App;
use Illuminate\Database\Eloquent\Model;
class RegCars extends Model
{
//
}
Since I have a different table name, so I add protected $table = 'regcars'; and assume that this model can now access the table by running query such as RegCars::where('user_id', $user_id); from controller. But I wasn't able to get anything by running it.
So I am wondering, how does this model able to run the query? Is the migration needed in order to do this? Is there still other area I need to set before I can run any query?
highly recommend to read docs or at least watch a tutorial.
what you get is a query build not a model or a collection of models. laravel(eloquent) doesnt exactly know what you want so you query database then get the data by methods that laravel gives you if assume you want a RegCars you need a method like first:
RegCars::where('user_id', $user_id)->first(); // now you have model
more info: https://laravel.com/docs/8.x/eloquent
I am using Laravel 5.6 and has a multi-auth funcitonality and it works fine. I have user and admin tables in my DB. How can i set a default value on admin table like NAME, EMAIL and PASSWORD? So everytime i run php artisan migrate:refresh i will have the default NAME EMAIL and PASSWORD in admin table? Thank you!
Without a little clarification there are two possible answers to your question. If you are asking about columns in your database tabled having default values this has already been answered but it is simply by chaining the method default on your attribute.
$table->tinyInteger('status')->default('1');
If you are asking about populating a row in your database whenever you migrate refresh. You can use seeders:
Laravel includes a simple method of seeding your database with test
data using seed classes. All seed classes are stored in the
database/seeds directory. Seed classes may have any name you wish, but
probably should follow some sensible convention, such as
UsersTableSeeder, etc. By default, a DatabaseSeeder class is defined
for you. From this class, you may use the call method to run other
seed classes, allowing you to control the seeding order.
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::table('users')->insert([
'name' => 'default_name',
'email' => 'default#mail.com',
'password' => 'password',
]);
}
}
And afterwards just call:
php artisan migrate:refresh --seed
class Product extends Model
{
/**
* Table name
* #var string
*/
protected $table = 'products';
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function buyerSupplier()
{
return $this->belongsTo('App\Models\Buyer', 'buyer_id');
}
}
Above is example code, if I call $this->buyerSupplier()->get() will it run MySQL?
Please, someone, tell me how this Laravel relationship is working?
The answer is Yes Laravel runs mysql queries behind the scene, here is a brief description from Laravel Official documents,
Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems.
The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.
And about the relationships queries Laravel uses Eloquent:
Eloquent relationships are defined as methods on your Eloquent model classes. Since, like Eloquent models themselves, relationships also serve as powerful query builders, defining relationships as methods provides powerful method chaining and querying capabilities.
And for more details about how to choose between relationships methods
read more from Laravel Official Documents
I'm trying to find a optimal way to save and access my paypal credentials on laravel from my Database.
I know it is common to save this kind of data on the .env file or a config file, but I need the user to save his credentials instead of mine.
So what I really need is save the paypal credentials and give the opportunity to personalize their credentials and other data.
There are probably many ways to do this, but the most secure way in my opinion is to use a database. You can use Laravel's Eloquent to talk with your database. It is also a good idea to encrypt the user's PayPal credentials before storing them in your database.
Here is a sample of what I have done in the past to start my database. You will of course have to create the table in your database.
<?php
namespace Application\UserCredentials;
use Illuminate\Database\Eloquent\Model as Eloquent;
class Credentials extends Eloquent
{
protected $table = 'credentials';
protected $fillable = [
'clientID',
'clientSecret',
'user_id'
];
}
Here is an example of what I have used to add this to your database.
<?php
use Credentials;
$userCredentials = Credentials->create([
'clientID' => $clientId,
'clientSecret' => $clientSecret
]);
This should get you started with what you can do with Eloquent in Laravel.