首页 > 解决方案 > Laravel Delete and Update

问题描述

I created a Post and a Get Request, Looks like this:

public function getAllCustomer()
{

    $customer = \App\model\Customer::get();
    return $view = View::make('test')->with('customer', $customer);
}

public function addNewCustomer(Request $request)
{
    $validatedData = $request->validate([
        'Title' => 'required',
        'Name' => 'required|max:255'

    ]);

    return \app\model\Customer::create($request->all());
}

So I can read all the data and create some new one, but now I want to delete them and/or update them, I couldnt find something really helpful, I would be very thankful for some help!

标签: phplaravel

解决方案


for updating you can define a route like this

Route::put('customer/{customer}' , 'CustomerController@update');

you should define a method_field('put') in your form and create a function called update in your controller

pulblic function update (Request $request , Customer $customer){
   $customer->update($request->all());
}

to update the fields that you want to be updated, you have to add them to $fillable array in your customer model, read about Mass Assignment in laravel and that because all Eloquent models are protected against mass-assignment by default.

for delete : route:

Route::delete('customer/{customer} , 'CustomerController@destroy');

a function for deleteing customer in your controller

public function destroy (Customer $customer){
  $customer->delete();
}

and add method_field('delete') to your form

Form example:

    <form  action="{{url("customer/{$customer->id}")}}" 
method="post">
         {{method_field('delete')}}
        //Html Elements Here
     </form>

after you get familiar with routes and controller you can make benefits of using

Route::resource('customer','CustomerController');

which will create all necessary route for you

Edited: please note that {customer} in route should be the id of the Customer you want to update or delete


推荐阅读