DEV Community

Hamid Semix
Hamid Semix

Posted on

Getting started with yuga-framework part 3 (Querying the database and more)

In today's tutorial, I am going to take you through how to comment on a post that is already in the database,
this requires to first query the database for that post, then attach a comment to it and then save the changes, so without any further ado, let's get started.

First we need to query the database for a given post say with id 1

Yuga comes with an ORM that might by handy at database manipulation, so, that's what we will use for querying our post from the database but first, lets create a route for accessing our post. Let's open routes/web.php file to create our route.

// routes/web.php

Route::get('/post/{id}', 'BlogController@getPost');

Now let's open app/Controllers/BlogController.php and add getPost method to our class

// app/Controllers/BlogController.php

public function getPost(Post $post, int $id)
{
    $post = $post->find($id);

    return $this->response->json(['post' => $post]);
}

Now let's go to the browser and vist http://localhost:8000/post/1

This must be your result
Post

Now let's edit

In the routes/web.php, let's add this route

// routes/web.php

Route::get('/post/{id}/edit', 'BlogController@editPost');

In the app/Controllers/BlogController.php, let's add the editPost method to the BlogController class but before that, let's first create a relation between the Post model and Comment model found in app/Models

In the app/Models/Post.php

// app/Models/Post.php

public function comments()
{
    return $this->hasMany(Comment::class);
}

In the app/Models/Comment.php

// app/Models/Comment.php

public function post()
{
    return $this->belongsTo(Post::class);
}

In the app/Controllers/BlogController.php

// app/Controllers/BlogController.php

public function editPost(Post $post, int $id): string
{
    $post = $post->find($id);

    // Let's create the comments from here
    // [`creator_name`, `post_id`, `comment_content`]
    $post->comments()->save(new Comment([
        'creator_name' => 'Hamid Semix',
        'comment_content' => 'This is the first comment'
    ]));

    return "Your comment has been saved";
}

Now let's edit our getPost method to incorporate comments to

// app/Controllers/BlogController.php

public function getPost(Post $post, int $id)
{
    $post = $post->with('comments')->where('id', $id)->first();

    return $this->response->json(['post' => $post]);
}

In the editor
Editor

This must be your result
Result

Top comments (0)