Home > other >  How to make a specific model in Laravel/Lumen according to JSON received from mobile app?
How to make a specific model in Laravel/Lumen according to JSON received from mobile app?

Time:06-05

I am building a web app (with Lumen) which will receive JSON data from a mobile app and store it. And it will also send data in the same JSON format. I have made the model of the data in the mobile app in Kotlin. Which will be serialized to JSON by the retrofit library.

data class Mouse(
   val id: Int,
   val name: String
)
data class Occasion(
   val id: Int,
   val name: String
)
data class Location(
   val id: Int,
   val name: String
)
data class Session(
   val id: Int,
   val name: String
)
data class Project(
   val id: Int,
   val name: String
)

data class LocOccLMouse(
   val loc: Location,
   val occ: Occasion,
   val lisMouse: List<Mouse>
)

data class SesLOLM(
   val ses: Session,
   val lisLOLM: List<LocOccLMouse>
)

data class SyncClass(
   val prj: Project,
   val lisSesLOLM: List<SesLOLM>
)

So I will be sending just the SyncClass from mobile app.

But I do not know how to make the same model in php Lumen. So that I can just receive the model and extract the data from it. And also to use it to respond with some data (in the same JSON format) for the mobile app. Is it possible to create the model from basic classes or do they need to inherit from eloquent model? And how do I create that model?

CodePudding user response:

They'r a lot of differents questions here. In first you want to create an API with Lumen that can receive and send JSON. In second place, you want to convert JSON in your back-end to Eloquent Model. lumen can translate your eloquent model to Json, with Responses. For your main task, you will create a Controller that handle your request from mobile app , something like this :

class MyClassNameApi extends controller{
  public function index(CustomRequestValidator $request){
    //Do the job aka $model = new Model($request->all())
    return responses()->json($customReponse,$httpCode)  
  }
}

I really recommands you to check the Requests lifecycle of lumen. Also don't forget to create some workflow UML to help you.

About Model

sample for LocOccLMouse :

<?php 
namespace App\Models
use Illuminate\Database\Eloquent\Model;

class LocOCCLMouse extends Models{
   public function loc(){
     $this->hasOne(Location::class)
   }
   public function occ(){
     $this->hasOne(Occasion::class)
   } 

   public function lisMouse(){
     $this->hasMany(Mouse::class)
   }

   //Etc....
}

I hope i can help you

  • Related