jkew

posts with static categories

Posted 10 months ago by jkew

Hi, Im a beginner and I have a doubt. When a user is in a page to create a new post he can select categories for the post using a select menu. These categories should be stored in a database table categories and there is a relation many to many between posts and categories, because a post can have many categories. But the categories are static, there are just 10, and its not possible in the system to create new categories.

But to load the categories in the database so the user can have access to them in the page of creating a new post, there is some way to do this in laravel or its better just insert manually in the database?

Relevant code for this context:

// Category Model:

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

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

}
Migration Post:

class CreatePost extends Migration
{

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

<?php

class CreateCategoriesTable extends Migration
{

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

<?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',

        ]);
}

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.