5

Laravel 5 version

I am working on a project with the new laravel 5 release and for some reason i cannot delete a post, when I press delete it just redirects me to the post show page with the id such as /post/3 and I get a blank white page, when I go back to index view I get all the posts and that one has not been deleted. Here is what I have below:

Posts migration file

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreatePostsTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('title')->default('');
            $table->string('slug')->default('');
            $table->text('body');
            $table->integer('author_id');
            $table->string('author');
            $table->string('featured_image');
            $table->softDeletes();
            $table->timestamps();
        });
    }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('posts');
    }

}

PostsController

use Input;
use Redirect;
use Storage;
use SirTrevorJs;
use STConverter;
use Validator;
use Image;
use Boroughcc\Post;
use Boroughcc\Http\Requests;
use Boroughcc\Http\Controllers\Controller;

use Illuminate\Http\Request;

class PostsController extends Controller {
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $posts = Post::all();
        return view('posts.index', compact('posts'));
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function update(Post $post)
    {
        //
        $this->middleware('auth');
        $input = array_except(Input::all(), '_method');
        $post->update($input);

        return Redirect::route('posts.show', $post->slug)->with('message', 'Post updated.');
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy(Post $post)
    {
        //
        //$post = Post::findOrFail($id);
        $post->delete();
        if($post->delete()) { 
            return Redirect::route('posts.index')->with('message', 'Post deleted.');
        }
    }

}

As far as i am aware, this is okay but I think its the delete method that is screwing with it all. In my routes file I have the route resources set up so in php artisan to display routes I can see the destroy route like so:

|        | GET|HEAD                       | posts                                                 | posts.index   | Boroughcc\Http\Controllers\PostsController@index                 |            |
|        | GET|HEAD                       | posts/create                                          | posts.create  | Boroughcc\Http\Controllers\PostsController@create                |            |
|        | POST                           | posts                                                 | posts.store   | Boroughcc\Http\Controllers\PostsController@store                 |            |
|        | GET|HEAD                       | posts/{posts}                                         | posts.show    | Boroughcc\Http\Controllers\PostsController@show                  |            |
|        | GET|HEAD                       | posts/{posts}/edit                                    | posts.edit    | Boroughcc\Http\Controllers\PostsController@edit                  |            |
|        | PUT                            | posts/{posts}                                         | posts.update  | Boroughcc\Http\Controllers\PostsController@update                |            |
|        | PATCH                          | posts/{posts}                                         |               | Boroughcc\Http\Controllers\PostsController@update                |            |
|        | DELETE                         | posts/{posts}                                         | posts.destroy | Boroughcc\Http\Controllers\PostsController@destroy

Post form with delete button

In here I have got a simple button that tells the form to delete the resource from the index list and take it from the table.

{!! Form::open(array('class' => 'form-inline', 'method' => 'DELETE', 'route' => array('posts.destroy', $post->id))) !!}
                    <li>
                        <img src="{!! $post->featured_image !!}" alt="" />
                        <a href="{{ route('posts.show', $post->id) }}">{{ $post->title }}</a>
                    </li>
                    (
                        {!! link_to_route('posts.edit', 'Edit', array($post->slug), array('class' => 'btn btn-info')) !!},
                        {!! Form::submit('Delete', array('class' => 'btn btn-danger')) !!}
                    )
                {!! Form::close() !!}

What I am getting is nothing, no post gets deleted at all. Any answers or points to the right place would be awesome.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
M dunbavan
  • 1,157
  • 5
  • 22
  • 57
  • Have you tried using forceDelete()? Are you sure the dependency injection is retrieving the post correctly? what happens if you just do a "return $post;" right before $post->delete()? does it return the correct model? – heisian Nov 03 '15 at 02:16

4 Answers4

6

I don't know how to do it with the static class Form but I found this problem some days ago using only HTML code.

This doesn't work:

<form action="{{ action('Controller@destroy') }}" method="DELETE">
...
</form>

This works fine:

<form action="{{ action('Controller@destroy') }}" method="POST">
    <input type="hidden" name="_method" value="DELETE">
    ...
</form>

Sources:

Samuele Colombo
  • 685
  • 2
  • 6
  • 20
1

how to send form by post applied to users:

View:

<form class="" action="{{ url('/home/destroy') }}" method="post">
  <li><button type="submit"><i class="fa fa-btn fa-sign-out"></i>Destroy user</button></li>
  <input type="hidden" name="id" value="{{Auth::user()->id}}">
  {{ method_field('DELETE') }}
  {!! csrf_field() !!}
</form>

Route:

Route::group(['middleware' => 'web'], function () {
 Route::delete('/home/destroy',[
  'as'=> 'home.destroy',
  'uses'=> 'homeController@destroy',
 ]);
});

Controller:

use app\User;
use Illuminate\Support\Facades\Auth;

protected function destroy(Request $request)
{
  $id= $request->id;
  if (Auth::user()->id == $id){
    $user= User::find($id);
    $user-> delete();
    Auth::logout();
    return redirect()->route('welcome');
  }else{
    return redirect()->route('home');
  }
}

if() is only to prevent a user deletes another and Auth::logout() is to clear user data in the session if you do not work with users will not need them, you must use == not === to compare $id and Auth::user()->id, $id works as string, and Auth::user()->id works as number.

This way is equivalent to using get with this code:

View:

<li><a href="{{ url('/home/delete', Auth::user()->id) }}"><i class="fa fa-btn fa-sign-out"></i>Delete user</a></li>

Route:

Route::group(['middleware' => 'web'], function () {
  Route::get('/home/delete/{id}', 'homeController@delete');
});

Controller:

protected function delete($id)
{
  if (Auth::user()->id == $id){
    $user= User::find($id);
    $user-> delete();
    Auth::logout();
    return redirect()->route('welcome');
  }else{
    return redirect()->route('home');
  }
}
0

You want to use Route model binding here.

You can go to the boot method in your app/Providers/RouteServiceProvider.php file and add in int:

$router->bind('posts','Boroughcc\Post');

to tell laravel the posts parameter (it's visible in route:list you provided) should be bound to thePost` model (Laravel by default will use id)

or you can do the same in app/Http/routes.php using:

Router::bind('posts','Boroughcc\Post');
Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • Hi Marcin, I have this in my routes file: `Route::model('posts', 'Post'); Route::resource('posts', 'PostsController'); Route::bind('posts', function($value, $route) { return Post::whereSlug($value)->first(); });` – M dunbavan Feb 21 '15 at 08:41
  • This still has not worked as you can see the routes already are in place – M dunbavan Feb 21 '15 at 08:47
  • @Mdunbavan So try to check what's inside `$post` in your `destroy` method: `dd($post->toArray());` – Marcin Nabiałek Feb 21 '15 at 09:13
  • okay so it gives me the post array which is fine but deleted_at is not filled in obviously `array:10 [▼ "id" => 3 "title" => "Project 3" "slug" => "project-3" "body" => "cddcddc" "author_id" => 0 "author" => "" "featured_image" => "/private/var/folders/mf/srx7jt8s2rdg0mn5hr98cvz80000gn/T/phpZb0VAC" "created_at" => "2015-02-07 17:17:31" "updated_at" => "2015-02-16 13:54:53" "deleted_at" => null ]` – M dunbavan Feb 21 '15 at 09:22
  • @Mdunbavan Have you added to your `Post` model: `use SoftDeletes;` ? In addition now you are running `delete` method twice in your `destroy` method of controller – Marcin Nabiałek Feb 21 '15 at 10:10
0

to delete a model, do this

$model -> find($id);
$model -> delete();

or simply

$model -> destroy($id);

to delete multiple rows

$model -> destroy ([1,2,3]);
mdamia
  • 4,447
  • 1
  • 24
  • 23