Laravel: passing dynamic table name to model e.g protected $table = "$tablename" - php

So my code successfully creates dynamic tables of the exact same structure (I need it this way for my own reasons).
However, the problem comes when I want to add data to any of the dynamically created table because I don't have a model for it, the way I have when I normally create tables/models.
So, I was wondering how can I work around this problem?
Can I use this kind of logic somehow?
namespace App;
use Illuminate\Database\Eloquent\Model;
class sys_cats extends Model
{
// I know we can't use variable in class like this
// but this is just to explain what kind of logic I have
// in mind.
$category = Session::get('catName');
protected $table = "$category";
protected $primarykey = 'id';
protected $fillable = [
.
.
.
So I assume, this way, we can use this model to dynamically change table name to the name stored in a session variable.
So we won't have to create a separate model for each of these tables.
Is this achievable? Or I must create a separate model file as well each time when I dynamically create a table in database?
I am sorry, if what I am suggesting is fundamentally wrong or anything related. I am pretty new to PHP and Laravel.
Waiting for your kind suggestions.
Thanks

better to use fluent query builder db
u can add dynamically table name with insert,update,read,delete
operation
for example
get record from db
DB::table($tableName)->all()
for insert
DB::table($tableName)->insert(['name' => $name]);
for automatically added created_at and updated_at add in migration
$table->timestamp('created_at')->default(\DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(\DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));

Related

Is it possible to define a function in the table property of Model Laravel?

Colleagues, help out. I have a list_books_hist(?) function in my database (the database is built on a separate scheme, not tied to migrations) (which we will go to the id and it returns a line from the table of outdated books)
class BooksListHist extends Model
{
protected $connection = 'db_main';
protected $table = 'lst_books_hist(?)'; //--> can I do like this?
}
Then how do I build a query by passing an ID card there? Using AddBinding? How can I work with the BooksListHist model in this case ?
BooksListHist::addBinding("id_book", "select")->select() ? But in this case it doesn't work

query builder equivalent of Model::query();

Good day, please, for some reasons I have to use query builder instead of Eloquent, the reason been that the name of my model is KidsCafe and if I use Eloquent, it will search for a table with myapp.kidscaves, but the name of the table is kidscafes this is throwing errors, so I have to use query builder in my interaction with the db.
Now, I have to implement search functionality, so how do I implement something like this using query builder
$kids = KidsCafe::query();
My question is how do I implement query(); using query builder, and also is there another way I can use eloquent without it
thank you in advance
You can manually specify a table name by defining a table property on your model:
class KidsCafe extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'kidscafes';
}
You can also use the setTable() function do dynamically use another table's name, something like this -
$kidscafes = new KidsCafe;
$kidscafes->setTable('kidscafes');

Eloquent (WITHOUT Laravel) get data from table with dynamic name

I'm sure this is a totally simple question but for the life of me I'm stuck here- we're using Eloquent outside of Laravel due to PHP restrictions. I have a support ticket tracking app that I'm trying to update.
The data structure of this app is such that each ticket is assigned a UUID on submission and a table with that UUID as its name is generated and all changes to the ticket are tracked as new entries in that table.
Following some tutorials on Eloquent I got our models and controllers set up and working but for each one I see that I'm defining the table name in the model itself. IE our ticket model is
namespace Models;
use \Illuminate\Database\Eloquent\Model;
class Ticket extends Model {
protected $table = 'tickets';
protected $fillable = [table columns here];
}
and anything called in the tickets controller correctly and successfully reads and writes data to our tickets table.
So... my question is: how would I go about reading/writing/creating/deleting those previously mentioned UUID tables?
I've tried the built in table selector (ie- DB::table(uuid here) and DB::setTable(uuid here) but to no avail. I get Fatal error: Call to undefined method Models\Database::setTable()
What I'm after is a model/controller that I can reuse for ANY dynamically-named table.
You could create a generic model and dynamically set the table name, like this:
namespace Models;
use \Illuminate\Database\Eloquent\Model;
class FormerUUIDTicket extends Model {
protected $table = 'some_table';
protected $fillable = [table columns here];
}
class SomeController
{
public function someAction()
{
$uuid = $_POST['uuid_field']; //some uuid, the table name
$model = new FormerUUIDTicket;
$model->setTable($uuid);
return $model->get(); //do anything using eloquent with proper table
}
}
Make sure that you always set the table name before use, or it will fail. Don't use static function either, for the same reason.

Laravel updating a hasMany relationship

In my system users can have many timesheets, timesheets can have many data.
I'm trying to update the data rows in the data_timesheet table. I'm using this:
$data = ['column_1' => 'value'];
$this->findTimesheetById($id)->data()->saveMany($data);
However, it's giving me the following error:
Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, array given
I know why it's giving me the error, because I need to send it a model as opposed to an array. How can I send in a model, when the values being passed are from a user form?
EDIT:
I can do this which works, but there must be a better way?
$data = $this->findTimesheetById($id)->data();
$data->delete();
$data->insert($data);
The way to do that is:
1) You create a file model and put it in the Models folder. That model can even almost empty, like this:
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Session;
use DB;
class Booking extends Model{
2) Then in the Controller you create an instance of that Model, like this
$theinstance = new Booking;
3) Then you use that object to have the values given, like this:
$theinstance->name = $name;
$theinstance->telephone = $telephone;
$theinstance->save();
That would be the way to save data.
Now, with regards to the update, at the Controller you can have something like this:
$photosslide = Property::returnPhotosSlide($id);
$propertydetails = Property::returnPropertyDetails($id);
$alsointown = Property::returnAlsoInTown($id);
return view('detailsproperty', compact('photosslide','propertydetails','alsointown'));
This sends the values from a Form into the Model
and once you are in the Model, just do an Update query.

Temporary property for Laravel Eloquent model

I have a Laravel Eloquent model User, which has a table with username and email columns. I need to add a property for the model on runtime, something like $user->secure. This property doesn't need to go to database.
When i add this property and hit $user->save() i get an error saying i don't have database column 'secure'. I can unset 'secure' before save but somehow it feels there should be a better way to do so. Any suggestions?
Just add an attribute to your class.
class User extends Eloquent {
public $secure;
// ...
}
Note that it is better to declare it protected and add corresponding accessors and mutators (getSecure and setSecure methods) to your model.
For those who still find this post (like I did), you may need to explicitly declare the property as null to prevent it from being automatically added to the attributes array, and thus being added to INSERT/UPDATE queries:
class User extends Eloquent {
public $secure = null;
// ...
}
Source: http://laravel.io/forum/02-10-2014-setting-transient-properties-on-eloquent-models-without-saving-to-database
If you intend to make use of that add-on property, then $append will blow your mind.
http://laraveldaily.com/why-use-appends-with-accessors-in-eloquent/

Categories