dynamitem
dynamitem

Reputation: 1669

Laravel 4 deletion by id

I can't find a way to delete my news. It returns me an 404 (not found) error.

my model (News.php):

    <?php

class News extends Eloquent {

    protected $table = 'aac_news';

    protected $fillable = array('author', 'title', 'content');
    public $timestamps = true;
}

my controller:

        <?php

    class AdminController extends BaseController {



    /**
     * News Repository
     *
     * @var News
     */
    protected $news;

    public function __construct(News $news)
    {
        $this->news = $news;
    }

/** ------------------------------------------
 *  News Functions
 *  ------------------------------------------
 */

    public function get_news()
    {

      return View::make('admin.news_managment')->with('newss', $this->news->all());
    }

    public function create_news()
    {

      return View::make('admin.create_news');
  }

  public function post_create_news()
  {
    $input = Input::all();

    $rules = array(
        'author' => 'required|min:4|max:255',
        'title' => 'required|unique:aac_news,title|min:4|max:255',
        'content' => 'required|unique:aac_news,content|min:10'
        );

    $validation = Validator::make($input, $rules);

    if ($validation->fails()) {

       return Redirect::back()->withErrors($validation);

   } else {

    News::create($input);
    return Redirect::to('news/index');
}
}

public function news_delete($newsId)
{
 $news = $this->news->findOrFail($newsId);
 $news->delete();
 return Redirect::back()->with('success', 'Your news post has been deleted.');
}
}

and my routes:

    # News Management
Route::get('admin/dash/news', 'AdminController@get_news');
Route::get('admin/dash/news/add', 'AdminController@create_news');
Route::post('admin/dash/news/add', 'AdminController@post_create_news');
Route::get('admin/dash/news/{id}/delete/', 'AdminController@news_delete');

It just returns my custom error 404 page. There are no errors in my console (laravel's PHP). I have the same function to delete my account, and it works.

Upvotes: 0

Views: 2012

Answers (1)

msturdy
msturdy

Reputation: 10794

Have you tried just finding the item using your News class?

public function news_delete($newsId)
{
    $news = News::find($newsId);
    $news->delete();
    return Redirect::back()->with('success', 'Your news post has been deleted.');
}

Though really you should check that it was deleted before you tell the user so. The delete() method returns the number of affected rows, so you should check if it's more than 0 when it comes back

Upvotes: 2

Related Questions