You can perhaps make a look up map?
$map = [
'table1' => TableOne::class,
'table2' => TableTwo::class,
];
$model = app($map[$table]);
$model->query()->where('foo', 'bar')->get(); //etc
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have list of URLs that display data tables that the user can update. Each of these tables has a matching model, however their names aren't always identical. For example:
tables/table1 // matches model TableOne
tables/table_two // matches model Table2
tables/table_3 // matches model Table3
The users can update these tables so I want to have the same script but get the model name or table name dynamically.
Should I do it by sending the URL then have a file that translates the URL to the matching model/table names. Or, should I output the exact model/table name in the Blade file as a hidden input then submit it with the form?
Ty
@Ligonsker Ok. Well at least this will help ensuring that you only allow certain tables. But are the colums the same on all or ?
The app() helper https://laravel.com/docs/9.x/helpers#method-app
And yes you can perhaps make a helper class for looking up the correct model.
ModelFinder::find($table);
and the class
class ModelFinder
{
public static function find($table)
{
$map = [
'table1' => TableOne::class,
'table2' => TableTwo::class,
];
if (!isset($map[$table]) {
throw new \Exception('Invalid table!');
}
return app($map[$table]);
}
}
Please or to participate in this conversation.