创建具有预定义类别的帖子

时间:2018-02-12 19:06:25

标签: laravel

我有一个帖子表和一个类别表。但它不可能创建新的类别,它们应该已经存在于数据库中,并且无法更改它们。你知道如何在laravel上正确构造这个逻辑吗?

此外,当创建帖子时,它应该最多有3个类别和发布日期。你知道如何在laravel,日期以及创建帖子时最多3个类别进行验证吗?我现在有这个验证:

 $this->validate($request, [
           ‘post_name’ => 'required|max:255',
           ‘post_categories’ => 'required',
            ‘post_date' => 'required',

        ]);

此背景的相关代码:

//类别模型:

class Category extends Model
{
    public function posts(){
        return $this->belongsToMany('App\Post’);
    }
}

//发布模型

class Post extends Model
{
    public function categories(){
        return $this->belongsToMany('App\Category');
    }

}

迁移帖子:

class CreatePost extends Migration
{

    public function up()
    {
        Schema::create(‘posts’, function (Blueprint $table) {
            $table->increments('id');
            $table->string(‘name’);
            …
            $table->timestamps();
        });
    }

迁移类别:

<?php

class CreateCategoriesTable extends Migration
{

    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }
}

//发布控制器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller
{

    public function index()
    {
    }

    public function create()
    {
        return view(‘app.createPost’);
    }


    public function store(Request $request)
    {
        dd($request->all());

        $this->validate($request, [
           ‘post_name’ => 'required|max:255',
           ‘post_categories’ => 'required',
            ‘post_date' => 'required',

        ]);
}

1 个答案:

答案 0 :(得分:0)

使用between规则

'post_categories' => 'required|array|between:1,3'

对于第一个问题,请使用firstOrCreate

foreach($request->post_categories as $categoryName){

   $category= App\Category::firstOrCreate(['name' => $categoryName]);

  $post->categories->attach($category->id);

}