Not sure, but you might want to have an "uncategorized" category and run an update to change all the posts with the old category to that one. Then delete the category.
Mar 5, 2017
6
Level 4
Remove category_id from post when category is deleted
I'm working on a blog and would like to be able to delete categories on the fly. I'd then like to find all associated posts and remove the category_id from the row.
CategoryController.php
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$category = Category::find($id);
$category->posts()->delete();
$category->delete();
Session::flash('success', 'The tag was successfully deleted.');
return redirect()->route('categories.index');
}
Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table = 'posts';
protected $fillable = [
'title',
'excerpt',
'body',
'slug',
'category_id',
];
public function category()
{
return $this->belongsTo('App\Category');
}
public function tags()
{
return $this->belongsToMany('App\Tag');
}
}
Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
protected $fillable = [
'name',
];
public function posts()
{
return $this->hasMany('App\Post');
}
}
Any ideas on how to make this work. Please advise!
Please or to participate in this conversation.