duanci6484 2017-11-10 15:42
浏览 99

Laravel:使用资源控制器更新表的单个字段

I have a Resource Controller (with all the actions: index, create, store, show, edit, update and destroy) and I was wondering what is the best approach to edit a single field column?

Let's say we have a Users table with name, email, password and active (active is a tiny int 0 or 1).

In the users management page, there is a button to activate/deactivate users (makes a request to the server to update the "active" field for the selected user).

Should I create a new method updateStatus in the Controller or is there a way to handle this using the update method?

I don't want, by mistake, allow empty values in the name, email or password when updating the "active" column, so I need to keep the validation rules (in short, all fields are required), but this means when updating the "active" field, I need to pass all the user data in the request.

At this point I'm very confused and all help will be appreciated.

Thanks in advance!

  • 写回答

2条回答 默认 最新

  • douao1854 2017-11-10 17:41
    关注

    It sounds like you are new to Laravel, and some key concepts can be hard to grasp.

    In my opinion the best way to do it would be via a Model class. This is slightly confused by the fact that Laravel has a built in Users model, so I'm going to use a different model as the example of how to update a db field.

    php artisan make:model MyData
    

    Will create a new empty model file for the MyData table in app/

    The file will look like this:

    <?php
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    
    class MyData extends Model
    {
        //
    }
    

    Even though there's nothing in there, it now allows you do alter the database table using Eloquent.

    In your controller add this to make sure the model is included:

    use App\MyData as MyData;
    

    The controller should have a method something like this if updating with user input from a form:

    public function updateStatus(MyData $myData, Request $request){
    
        $myData->where('id', $request->id)->update(['active' => $request->active]);
    }
    

    You could do the exact same thing like this:

    public function updateStatus(Request $request){
      $data = MyData::find($request->id);
      $data->active = $request->active;
      $data->save();
    }
    

    Both approaches make sense in different circumstances.

    See https://laravel.com/docs/5.5/eloquent#updates

    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能