jeudi 8 mars 2018

Generic creation of Model / DB entry with Eloquent / Laravel 5.x

I'm trying to build a very generic function that receives a model name, and id and an array of values to update an existing model or create a new model, when the id value is empty or cannot be found (in my case)

The problem I'm having is that I cannot find the right way to generic create the new Model like I would usually do: $mymodel = new Mymodel();

Here is the relevant part of the function. It is not working and I dug already into the code in the Illuminate\Database folder

// lets get the model and then we update and save
$model = DB::table($request->input("model")."s")->where('id',$request->input("id"))->first();

if(!$model){
   $model = DB::table($request->input("model")."s")->new();
}

 // This part is not tested yet, but this part should set all the 
 // values from an Array of JSON objects, I will get that part to work
 foreach(json_decode($request->input("values")) as $value){
     $model->attributes[$value->name] = $value->value;
 } 

Does anyone have an idea how I could accomplish this in the easiest way? I don't really want to register all Models I have in a seperate function and create it there. If possible I want to keep it super-generic.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2HkKt81
via IFTTT

Aucun commentaire:

Enregistrer un commentaire