简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM