方法返回变量

时间:2019-02-17 15:30:21

标签: php laravel lumen

我写了一个小游戏供学习,但我陷入了困境,我有一个类,那里有生成报告的方法,当我从Controller站点调用任何方法时,这会在对象中返回类变量。

调用方法_Get或_Create返回:

{"id":null,"character_id":1,"name":null,"desc":null}

班级:

class GenerateRaport {
    public $id;
    public $character_id;
    public $name;
    public $desc;

    public function _Get() {
        $raport = PlayerRaport::where('character_id', $this->character_id)->orderBy('created_at', 'desc')->get();
        return $raport;
    }

    public function _Create() {
        $new = new PlayerRaport();
        $new->character_id = $this->character_id;
        $new->name = $this->name;
        $new->desc = $this->desc;
        $new->save();
        return $new;
    }
}

控制器:

class RaportController extends Controller
{
    public function index(Request $request) {
        $raport = new GenerateRaport();
        $raport->character_id = \Auth::user()->character_id;
        $raport->_Get();
        return response()->json($raport, 200);
    }

    public function create(Request $request) {
        $raport = new GenerateRaport();
        $raport->character_id = \Auth::user()->character_id;
        $raport->name = "Name";
        $raport->desc = "Description";
        $raport->_Create();
        return response()->json($raport, 201);
    }
}

@编辑:

class PlayerRaport extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'id', 'name', 'desc', 'character_id', 'viewed'
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [

    ];
}

1 个答案:

答案 0 :(得分:0)

我认为您没有将返回的值传递到响应中,这就是为什么json值为null的原因。 (请参阅@Jigius评论)

此外,我看到您创建了GenerateReport,因此viewed信息不会显示在json响应中。

虽然可以执行,但您也可以查看Laravel的Eloquent: API Resources(如果返回多行,则可以查看Resource Collections)。 通过为解决方案实现雄辩的资源,您可以节省很多精力。

找到一个样品

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class PlayerRaport extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'desc' => $this->desc,
            'character_id' => $this->character_id
        ];
    }
}
use App\PlayerRaport;
use App\Http\Resources\PlayerRaport as PlayerRaportResource;

class RaportController extends Controller
{
    public function show(Request $request) {
        return new PlayerRaportResource(PlayerRaport::find(1));
    }
}