Posts Laravel

$ php artisan make:model Post --migration --controller --resource --facto
ry

   INFO  Model [app/Models/Post.php] created successfully.

   INFO  Factory [database/factories/PostFactory.php] created successfully.

   INFO  Migration [database/migrations/2023_05_14_123419_create_posts_table.php] created successfully.

   INFO  Controller [app/Http/Controllers/PostController.php] created successfully.
  • A Post will have the following properties:
    • Title
    • Body 
    • Featured Image 
    • Slug

app/Models/Post.php

 

add a $fillable property to your Post class. 

 <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    public $fillable = [
        'title',
        'body',
        'slug',
        'featured_image',
        
    ];
}

The make command above will create a database migration file that built the database columns you need to support your posts.

 

    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->timestamps();
            $table->string('title');
            $table->longText('body');
            $table->string('featured_image')->nullable();
            $table->string("slug", 100)->nullable();
        });
    }

Then run the php artisan migrate command to build the table.

$ php artisan migrate

   INFO  Running migrations.

  2023_05_14_123419_create_posts_table ................................................................................................... 65ms DONE
  2023_05_14_123639_create_stories_table ................................................................................................. 74ms DONE

Create factories

 

 

php artisan tinker

//preview the creation of Post objects
Post::factory()->count(5)->make();
//actually make in databse 
Post::factory()->count(5)->create();

later you can remove these if you want

php artisan tinker

DB::table('stories')->truncate();

 

Create Views 

We need a page -- a view -- to list all the Post in the dabase

Create a file in resources/views post.blade.php