Laravel 5.2 - creating a model from a variable - php

I am trying to access dynamically models so that I can get the count for each of them depending on which string I pass to the function.
This is what my function in the controller looks like:
public function numberOf(Request $request){
$modelName = $request['option'];
$model = new $modelName;
$data = $model->count();
return json_encode($data);
}
But when I pass a string, like in this case 'Article' I get an error:
Fatal error: Class 'Article' not found
Even though I am calling it in the controller:
use App\Article;

I had to add App to model name, so that my function looks like this now and everything works fine now:
$modelName = 'App\\'.$request['option'];
$model = new $modelName;
$data = $model->count();
return json_encode($data);

Related

Import Model via Ajax Request Laravel - without namespacing the model

I am trying to import a model via an Ajax request without namespacing the model.
public function dataTypeRender(Request $request)
{
$input = request()->all();
$model = $request->input('model'); //this is the model name
$cols = $request->input('cols');
$modelTest = $model::all(); //not working
dd($modelTest);
}
Is there a way to do this? I'm trying to then do something with the model data.
I think without namespace it gonna be a little harder, because your model could be any model, but i think this could help you.
public function example(Request $request){
$data = $request->all(); //get All data request
$namespace = 'App\\'; //set namespace
$modelWithNameSpace = $namespace.$data['model']; //concat namespace and model name
$model = str_replace("'", "", $modelWithNameSpace); //remove quotes (idk if it's the best approach)
return $model::all(); //return the modell with all
}
This seemed to work nicely.
$model = 'App\\' . $request('model'); // adjust for the namespace/folder where you put your models
$data = (new $model)->all();
or
$data = (new $model)->find(1);

Yii2 Override Rest Api actioncreate method

can anyone tell me how to override actioncreate and actionupdate method yii2 rest api..
class CabController extends ActiveController
{
public $modelClass = 'api\modules\v1\models\Cab';
public function actions(){
$actions = parent::actions();
unset($actions['create']);
unset($actions['update']);
return $actions;
}
public function actionCreate(){
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model = $this->modelClass;
$model->load(Yii::$app->request->post());
$cur_time = date('Y-m-d H:i:s');
$model->date_created = $cur_time;
$$model->save(false);
}
If i do like this mean i got error like 500 internal server error and error message like Call to a member function load() on a non-object ..how to solve this issue..
Thanks...
You are not creating object, instead you are assigning string api\modules\v1\models\Cab to $model variable. Change assigning part to:
$model = new $this->modelClass;
In case of "Class not found" error add leading backslash to class name: \api\modules\v1\models\Cab.
Related answers about creating object from string:
Creating PHP class instance with a string
Dynamically create PHP object based on string
How to create object from String?

Laravel 5 - Namespace + Dynamic Model

I have a very basic function to delete stuff on a simple website on Laravel 4.x that works like this:
public function delete()
{
...
$Model = Input::get('Model');
$Action = $Model::find($Id);
...
}
Now on Laravel 5, I'm trying to do the same but so far I can't because the namespaces. Since the $Model is dynamic I don't want to make use for everything.
And something like this:
use App\C\Models as Model;
public function delete()
{
...
$Action = Model\$Model::find($Id);
...
}
Simple do not works. What'd be the right approach to get this to work?
Simply store the namespaced classname as a string first:
$Model = Input::get('Model');
$NamespacedModel = '\\Model\\' . $Model;
$Action = $NamespacedModel::find($Id);
In the same case, My code is like this...
public function FunctionName(Request $request)
{
$modelName = $request->model;
$model = '\\App\\Models\\'.$modelName;
$q = $model::find($request->id);
$q->someColumn = 'someValue';
$q->save();
return back();
}
Note: I am using Laravel 8

Laravel/PHP: New Instance of Model Class within Method of This Model

New to Laravel and still fresh to OOP! I'm assuming this has more to do with OOP than strictly Laravel.
So my main problem is that I am trying to pass all rows from a database table called 'fin_income_category' via a method in my model called Income to a controller called PlannerController. To do this I have created a static method within Income called getIncomeCategories()
First of all, here is my __construct method within Income:
public function __construct($income, array $attributes = array()){
parent::__construct($attributes);
$this->table = $income;
}
And here is the getIncomeCategories method also within Income:
public static function getIncomeCategories(){
$category = new self('fin_income_category');
$categories = $category->all();
return $categories;
}
Finally, here is the edit($id) method within the PlannerController where I am to call this method and pass the categories along to my view. Note that only the first statement in this function is the one in question...the others work fine:
public function edit($id)
{
$income_categories = Income::getIncomeCategories();
$newIncome = new Income('fin_income');
$newRecord = $newIncome->where('id', '=', $id)->get();
return View::make('planner.edit', array('record'=>$newRecord, 'categories'=>$income_categories));
}
When I run the code like this I receive an error from Laravel:
ErrorException
Missing argument 1 for Income::__construct(),
called in /opt/lampstack/frameworks/laravel/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 615 and defined
In other cases where I have instantiated a new Income I have not received this error.
Change the getIncomeCategories() to this
public static function getIncomeCategories(){
$category = new self('fin_income_category');
return $category->get()->toArray();
}
The reason why your code didn't work is because the eloquent all() found in
Illuminate\Database\Eloquent\Model; the code snippet is found below
public static function all($columns = array('*'))
{
$instance = new static;
return $instance->newQuery()->get($columns);
}
is instantiating a static class which is bound to the called class which is your Income Model Class in your case, and in the process requesting the arguments in the constructor

Laravel database Insert error

I trying to insert data to database using laravel 4 eloquent model. But throws the error:
"Call to undefined method Illuminate\Support\Facades\Request::save() "
I am new to laravel don't know where I Have gone wrong.
my UsersController.php code
public function postRequest() {
$request = new Request;
$request->vms = Input::get('vms');
$request->location = Input::get('location');
$request->descr = Input::get('descr');
$request->status = Input::get('status');
$request->save();
}
My Request.php Model
<?php
class Request extends Eloquent {
protected $table = 'requests';
protected $fillable = array('vms', 'location', 'descr', 'status');
public function ruser() {
return $this->hasOne('Ruser'); // this matches the Eloquent model
}
}
The problem is that your Request model name conflicts with Laravel Request class. You have two options:
1) Namespace your model:
<?php namespace App;
class Request extends Eloquent {
...
}
Then use it as:
$request = new App\Request;
2) Rename your model.
Seems like your hitting the laravel "Request" facade, instead of your Request model.
Could you try to prefix your new class call with the correct namespaces?
$request = new yourname\yourpackage\Request();
Or, best of all, call it something else?

Categories