Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete row from database table with Laravel 5.2

Recently I've started with Laravel 5.2 and I'm trying to make delete button which will delete row from database. Very basic and trivial but seems I can't make it.

I'm following documentation for delete: https://laravel.com/docs/5.2/queries#deletes

And I have made this. My route:

Route::post('flags/destroy/{delete}', 'FlagsController@destroy')->name('admin.flags.destroy');

Button in the view

{!! Html::linkRoute('admin.flags.destroy', 'Delete', $flag->report_id) !!}

and the controller

public function destroy(Request $request){

    $report = $request['report_id'];      

    Report::find($report);

    $report->delete();        
    $request->session()->flash('alert-success', ' Report is deleted successfully.');

    return redirect()->route('admin.flags');
}

I've tried solutions from other threads but I always got error:

MethodNotAllowedHttpException in compiled.php line 8936:

New error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'reports.id' in 'where clause' (SQL: select * from `reports` where `reports`.`id` is null limit 1

Why is searching for id instead of report_id?

UPDATE:

button

{!! Html::linkRoute('admin.flags.destroy', 'Delete', $flag->report_id) !!}

Controller

public function destroy(Request $request){

    $report = $request['report_id'];      

    dd( $request->input('delete'));

    Report::where('report_id', $report)->first();

    $report->delete();        
    $request->session()->flash('alert-success', ' Report is deleted successfully.');

    return redirect()->route('admin.flags');
}

Route

Route::get('flags/destroy/{delete}', 'FlagsController@destroy')->name('admin.flags.destroy');

Update 2: This seems to work but is it secure enough? view:

 {!! Form::open(array('route' => array('admin.flags.destroy', $flag->report_id), 'method' => 'get')) !!}
        <button type="submit">Delete</button>
 {!! Form::close() !!}</td> 

Controller

public function destroy($report_id){

  Report::destroy($report_id);
  //$request->session()->flash('alert-success', ' Report is deleted successfully.');

  return redirect()->route('admin.flags');
}
like image 497
VLS Avatar asked Jan 18 '17 09:01

VLS


2 Answers

I think your code need to update like:

public function destroy($delete){

   $report = $delete;      

   $rsltDelRec = Report::find($report);

   $rsltDelRec->delete();        
   $request->session()->flash('alert-success', ' Report is deleted successfully.');

   return redirect()->route('admin.flags');
}

Hope this work for you!

like image 88
AddWeb Solution Pvt Ltd Avatar answered Sep 22 '22 01:09

AddWeb Solution Pvt Ltd


Try this:

Controller:

  public function destroy(Report $report){

          $report->delete();

          return redirect()->route('admin.flags');

    }
like image 41
MevlütÖzdemir Avatar answered Sep 22 '22 01:09

MevlütÖzdemir