Laravel import model in function - php

I'm trying to import the model in function and call create function of the specific model.
I know which model to call from Route::currentRoute();, so it must look like
$model = Route::currentRouteName() // return like 'Blog/Post'
$create = new App\Models\$model::create($request->input());
Any ideas on how to do it in that way?

You must put the full model path into the string, then it will work.
Also make sure that you replace forward slashes with backslashes.
And if you use 'create' you don't need 'new'.
Here the final result:
$model = str('Blog/Post')->replace('/', '\\');
$fullPath = 'App\Models\\' . $model;
$create = $fullPath::create($request->input()]);

We can just use call it putting a full path of the model. for eg:
public function callModel(Request $request){
$create = App\Models\$model::create($request->input());
dd($create);
}

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);

Is there any way to access laravel model dynamically through variable when model name is stored in variable?

Basically what I need to do is:
$x = 'Admin';
$model = new \ReflectionClass($x);
$model->getFieldList();
Where I have Admin model inside app folder.
Obviously, this doesn't work. Does anyone have any idea? Can it be done?
Firstly you need to add the namespace to your model. By default this is App\. So your string would have to be "\App\Admin". Now you can simply create a class instance using this string.
$x = '\\App\\Admin';
$model = new $x();
you can do this, but you need to use the fully qualified class name.for example My models are in the Model directory :
$model = 'App\Model\User';
$user=$model::where('id', $id)->first();
i use something like that in the controller constructor. here what i use:
1)first declare a variable in parent controller lets say:
$route_model_name and $model_location.
then add this to each child controller:
function __construct() {
parent::__construct();
$this->setRouteModelName( 'model_route_name' );
$this->setModelLocation( 'App\Models\ModelName' );
}
then you add a method in the parent controller to initialize the model class in order to be ready for making queries:
/**
* #return mixed
*/
protected function getModelClass() {
return app( $this->model_class );
}
then you can change the model location and route in each of the child controllers and still use the same method in the parent controller:
public function edit( $id ) {
return $this->getModelClass()::where( 'id', $id )->first();
}
$model = 'App?Models?'.$model;
$model = str_replace('?','\\',$model);
return $model::products()->paginate();

Laravel calling model with variable in controller

I am using one function in controller for inserting in several different tables with different Models. I mean that in controller model is variable.
This code bellow works perfectly but i don't like syntax, i am pretty sure there must be some other ways than str_replace for calling model with \App\ in front of it's name.
Calling only by Model name without \App\ causes laravel error Class not found. I have written use \App\ModelName in controller's file but it still does't works.
public function storeCommon(Request $request){
$model = '"\App\"'. $request->model;
$model = str_replace ( "\"", "", $model ) ;
........
........
$row['text'] = $request->text;
........
........
$common = $model::create($row);
}
I would rather define array of possible models and use it within the code. This way you will protect your code against call for unwanted models and off course your code will be much readable:
protected $possibleModels = [
'Model1' => \App\Model1::class,
'Model2' => \App\Model2::class,
...
];
public function storeCommon(Request $request){
if (!isset($this->possibleModels[$request->model])) {
abort(404);
}
$model = $this->possibleModels[$request->model];
$row['text'] = $request->text;
...
$common = $model::create($row);
}

Laravel calling a controller function from a model factory

I am building some tests in my Laravel 5.5 project.
In my GalleryFactory I need to generate a 'link', I have written this code inside a function in my GalleriesController like so;
private function generateUrlLink()
{
$generatedLink = str_random(8);
$existingGalleryWithGeneratedLink = Gallery::where('link', $generatedLink)->first();
while (!is_null($existingGalleryWithGeneratedLink)) {
$generatedLink = str_random(8);
$existingGalleryWithGeneratedLink = Gallery::where('link', $generatedLink)->first();
}
return $generatedLink;
}
I don't want to write this code twice in the controller and also the factory as i might want to modify it someday, so im wondering what the best way of going about this would be?
Any help would be fantastic.
Thanks.
The best way to go about this is to write this function in the eloquent model instead of the controller and then calling the function from the model.
public static function generateUrlLink()
{
$generatedLink = str_random(8);
$existingGalleryWithGeneratedLink = Gallery::where('link', $generatedLink)->first();
while (!is_null($existingGalleryWithGeneratedLink)) {
$generatedLink = str_random(8);
$existingGalleryWithGeneratedLink = Gallery::where('link', $generatedLink)->first();
}
return $generatedLink;
}
Hopefully, this works.

Laravel 5.2 - creating a model from a variable

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);

Categories