Skip to content

Commit b9858f1

Browse files
committed
create post Mutation
1 parent 1ed979c commit b9858f1

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<?php
2+
3+
namespace App\GraphQL\Mutations;
4+
5+
use App\Models\Post;
6+
use Error;
7+
use Illuminate\Support\Facades\Auth;
8+
9+
final class CreatePost
10+
{
11+
/**
12+
*
13+
* @param array{} $args
14+
*/
15+
public function __invoke($_, array $args)
16+
{
17+
$quard = Auth::guard("api");
18+
if (!$quard->user()) {
19+
throw new Error("Invalid credentials.");
20+
}
21+
$user = $quard->user();
22+
23+
$post = Post::create([
24+
"title" => $args["title"],
25+
"content" => $args["content"],
26+
"category" => $args["category"],
27+
"author" => $user->id,
28+
"likes" => 0,
29+
"views" => 0,
30+
"isPublished" => true
31+
]);
32+
return $post;
33+
}
34+
}

app/Models/Post.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ class Post extends Model
1111
{
1212
use HasFactory;
1313

14+
protected $fillable = ["title", "content", "author", "likes", "category", "views", "isPublished"];
15+
1416
public function author(): BelongsTo
1517
{
1618
return $this->belongsTo(User::class, "author");

graphql/post.graphql

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,12 @@ extend type Query {
66
myPosts: [Post]! @guard
77
postsByLike(likes: Int! @eq): [Post] @find
88
countOfPosts: Int!
9+
}
10+
11+
extend type Mutation {
12+
createPost(
13+
title: String!,
14+
content: String!,
15+
category: Int!,
16+
): Post! @guard
917
}

0 commit comments

Comments
 (0)