【问题标题】:Return varying fields based on Route根据 Route 返回不同的字段
【发布时间】:2014-09-12 05:40:24
【问题描述】:

Laravel 在模型中提供了“受保护”变量来隐藏 JSON 中的某些字段,但我想知道如何只返回某些路由的某些字段。例如,而不是返回

Alert::where('alert_id', $id)->first();

转储所有不在“受保护”数组中的字段,例如:

id: 139
alert_id: "8336f6d2-e191-4014-9316-2c7c93e3ada2"
status: "notified"
member_id: 16
organization_id: 1
type: "timer"
minutes: 20
lat: "45.86"
lon: "-90.11"
address: "US Highway for Road 519, Chequamegon National Forest, Park Falls, WI 54552, USA"
phone: ""
created_at: "2014-07-16 14:29:07"
updated_at: "2014-07-21 11:08:01"
user_id: 0

我希望能够指定,仅返回“纬度”和“经度”列,仅针对此特定路线

这可能吗?

【问题讨论】:

    标签: laravel laravel-4 eloquent laravel-routing


    【解决方案1】:

    小心 Laravel 使用 guardedfillable(相反)来防止批量赋值漏洞,并使用 hidden 从你的集合结果中隐藏像 password 这样的字段。

    作为一般经验法则,对您的大多数模型使用 guarded 属性:

    protected $guarded = ['id', 'created_at', 'updated_at'];
    

    现在只调用特定的列,这样做:

    $alert = Alert::select('id', 'lat', 'lon')->first();
    
    return View::make('myview', compact('alert'));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-05
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多