Got a small problem I need help solving out, I'm using laravel version 8.
So I have 3 different databases which have the same tables, I made a model for each database.
So for reference:
- Model
DB1entries
- DB1 -entries_table
- Model
DB2entries
- DB2 -entries_table
- Model
DB3entries
- DB3 -entries_table
So when sending a request i want all requests get to the same controller but the database can be changed depending on the request DB selected, can be with a param on the route.
for example:
/db1/store
would go toEntriesController
and create the entry in DB1
/db2/store
would go toEntriesController
and create the entry in DB2
but the "set" for the model wouldn't be the store function in EntriesController
.
I just don't want to use the same function to set the model for each function inside the controller, I want to create it dynamically in the constructor or any other solution.
My Answer:
One way to achieve this is by using middleware to set the model based on the route parameter before the request reaches the controller. Here's an example of how you can do this:
1. Create a middleware that sets the model based on the route parameter:
php
php artisan make:middleware SetModelFromRouteParameter
In the middleware class, you can set the model based on the route parameter like this:
php
namespace App\Http\Middleware;
use Closure;
class SetModelFromRouteParameter
{
public function handle($request, Closure $next)
{
$routeParameter = $request->route('parameter_name'); // Replace 'parameter_name' with the actual parameter name
switch ($routeParameter) {
case 'db1':
$model = new DB1entries();
break;
case 'db2':
$model = new DB2entries();
break;
case 'db3':
$model = new DB3entries();
break;
default:
// Handle default case
break;
}
app()->instance('model', $model);
return $next($request);
}
}
2. Register the middleware in the `app/Http/Kernel.php` file:
php
protected $routeMiddleware = [
// Other middleware
'setModel' => \App\Http\Middleware\SetModelFromRouteParameter::class,
];
3. Apply the middleware to the routes that need to set the model:
php
Route::group(['middleware' => 'setModel'], function () {
Route::post('/{parameter_name}/store', 'EntriesController@store');
});
4. In your controller, you can access the model using the `app()` helper:
php
use Illuminate\Support\Facades\App;
class EntriesController extends Controller
{
public function store(Request $request)
{
$model = app('model');
// Use the model to create the entry
return response()->json(['message' => 'Entry created successfully']);
}
}
This way, the model will be set based on the route parameter before the request reaches the controller, allowing you to dynamically switch between different models based on the route.
Rate this post
5 of 5 based on 6717 votesComments