简体   繁体   English

如何在 laravel 8 中创建具有一对多关系的 API?

[英]How to Create API with one to many relationship in laravel 8?

I want to create an API for a report store and there is an option to add more than one violator.我想为报表存储创建一个 API,并且可以选择添加多个违规者。

I have a problem, when I add a violator, in POSTMAN it displays the error "Call to a member function getClientOriginalName() on null".我有一个问题,当我添加违规者时,在 POSTMAN 中它显示错误“呼叫成员 function getClientOriginalName() on null”。

How to fix it?如何解决? or how to properly create an API with attach data one to many relationship?或者如何正确创建一个 API 与附加数据一对多关系?

the following, the code that I have made;以下是我制作的代码;

Controller.php Controller.php

    public function store(ReportRequest $request)
    {
        try {
            
            $report = Report::create([
                'category_id'       => $request->category_id,
                'user_id'           => Auth::user()->id,
                'title'             => $request->title,
                'description'       => $request->description,
                'incident_date'     => $request->incident_date,
                'injured_victims'   => $request->injured_victims,
                'survivors'         => $request->survivors,
                'dead_victims'      => $request->dead_victims,
                'location'          => $request->location,
                'latitude'          => $request->latitude,
                'longitude'         => $request->longitude
            ]);

            $data[] = array(
                    'violator_photo' => $request->file('violator_photo'),
                    'violator_name'    => $request->violator_name,
                    'violator_age'   => $request->violator_age,            
                    'violator_phone' => $request->violator_phone 
                    );
            
            foreach ($data as $key ) {   

                $photo = $key['violator_photo'];
                $fileName = time().'_'.$photo->getClientOriginalName();
                $filePath = $photo->storeAs('images/violators', $fileName, 'public');

                Violator::create([
                    'report_id' => $report->id,
                    'name'      => $key['violator_name'],
                    'photo'     => $filePath,
                    'age'       => $key['violator_age'],
                    'phone'     => $key['violator_phone'],
                ]);       
            }    
            
            return response()->json([
                'status' => '200',
                'message' => 'success',
                'data' => $report,
            ]);
        } catch (\Exception$err) {
            return $this->respondInternalError($err->getMessage());
        }
    }

在此处输入图像描述

try it with this code用这段代码试试

public function store(ReportRequest $request)
{
    try {

        $report = Report::create([
            'category_id'       => $request->category_id,
            'user_id'           => Auth::user()->id,
            'title'             => $request->title,
            'description'       => $request->description,
            'incident_date'     => $request->incident_date,
            'injured_victims'   => $request->injured_victims,
            'survivors'         => $request->survivors,
            'dead_victims'      => $request->dead_victims,
            'location'          => $request->location,
            'latitude'          => $request->latitude,
            'longitude'         => $request->longitude
        ]);
        if($report){
            if($request->hasFile('violator_photo')) {
                $violator_photo=$request->file('violator_photo');
                $fileName = time().'_'.$violator_photo->getClientOriginalName();
                $filePath = $violator_photo->storeAs('images/violators', $fileName, 'public');
            }

            Violator::create([
                'report_id' => $report->id,
                'name'      => $request->violator_name,
                'photo'     => $filePath?:'',
                'age'       => $request->violator_age,
                'phone'     => $request->violator_phone,
            ]); 
        }
        
        return response()->json([
            'status' => '200',
            'message' => 'success',
            'data' => $report,
        ]);
    } catch (\Exception$err) {
        return $this->respondInternalError($err->getMessage());
    }
}

The error getClientOriginalName(), I think that is because the "violator_photo" is not a file, but it's a string/text错误getClientOriginalName(),我认为这是因为“violator_photo”不是文件,而是字符串/文本

so, if you want to send file on a json request, the simple way is to convert the file to base64因此,如果您想在 json 请求上发送文件,简单的方法是将文件转换为 base64

and on the controller, you can decode it, and save the file在 controller 上,您可以对其进行解码并保存文件

here is the example how to decode it, there one thing you need to check for the base64.这是如何解码的示例,您需要检查一件事 base64。 Some of base64 encode, add extra information about the file type, for example if the file is image png, the data is look like this部分 base64 编码,添加有关文件类型的额外信息,例如如果文件是图像 png,则数据如下所示

data:image/png;base64,iVBORw0KGg..rest of base64

so if the data look like this you need to remove the information and just get the base64 simply you can do it whit this code因此,如果数据看起来像这样,您需要删除信息并获取 base64 只需使用此代码即可

$str ="base64 code";
$converted = substr($str, strpos($str,',')+1);
$image = base64_decode($base64_str);
$filename = "the file name.png"; // or you can get the extension name by the information the include on the first of base64
$path = "images/violators/";
Storage::disk('your disk')->put($path.$filename, $image, 'public');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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