I have a number of functions that are used by most of my models
so it makes sense to store them centrally rather than repeating code.
For example, I have a function that finds a random row from whichever table I need:
function getRandomRow() {
$rowCount = DB::connection('mydatabasename')
->table('my_table_name')
->selectRaw("FLOOR(RAND() * COUNT(*)) AS offset")
->first();
$offset = $rowCount->offset;
$randomRow = DB::connection('mydatabasename')
->table('my_table_name')
->select()
->offset($offset)
->limit(1)
->first();
return $randomRow;
}
I've looked at inheritance (extends) and traits - as well as the docs on polymorphic relations - but it's not clear which is the most efficient and how to access the table name (associated with the model being used) within the common function.
My questions:
- where do I put this function so that it can be used by all models ?
- how do I write the code so that the 'my_table_name'
uses the correct model table ?