Skip to content

Instantly share code, notes, and snippets.

@ShaneRich5
Last active May 20, 2025 04:56
Show Gist options
  • Save ShaneRich5/8ee4d42778fab5e1bd81e1418e54805c to your computer and use it in GitHub Desktop.
Save ShaneRich5/8ee4d42778fab5e1bd81e1418e54805c to your computer and use it in GitHub Desktop.
Fundamentals 3
// PostController::store
public function store(Request $request)
{
$data = $request->validate([
'title' => 'required|string|max:255',
'body' => 'required|string',
]);
if (strlen($data['body']) < 50) {
return response()->json(['error' => 'Post body must be at least 50 characters.'], 422);
}
$post = Post::create([
'user_id' => auth()->id(),
'title' => $data['title'],
'body' => $data['body'],
'published' => false,
]);
return response()->json($post, 201);
}
// posts
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('title');
$table->text('excerpt')->nullable();
$table->text('body');
$table->enum('status', ['draft', 'published', 'scheduled'])->default('draft');
$table->timestamp('published_at')->nullable();
$table->timestamps();
});
// comments
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->foreignId('post_id')->constrained()->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->text('body');
$table->timestamps();
});
// users
public function posts()
{
return $this->hasMany(Post::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
// posts
public function author()
{
return $this->belongsTo(User::class, 'user_id');
}
public function comments()
{
return $this->hasMany(Comment::class);
}
// comments
public function post()
{
return $this->belongsTo(Post::class);
}
public function author()
{
return $this->belongsTo(User::class, 'user_id');
}
User::factory()
->count(5)
->has(
Post::factory()
->count(3)
->hasComments(2),
'posts'
)
->create();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment