zerosAndOnes's avatar

Recommendation: Any course (free/paid) to learn laravel API for the sake of using it with nuxtjs, etc

I have built apps by using laravel, and livelier, but I have never done much with the API part (except making todo apps with it and vuejs(standalone)).

But I am more curious now, and I want to learn how to make apps with laravel api to return data with relationships.

For example, building a multi user blog where a user has many posts linked to them, etc.

So I need a recommendation as to where I might be able to find something that covers something like this.

Thanks.

0 likes
9 replies
Reached's avatar
Reached
Best Answer
Level 11

It’a a very interesting topic for sure, and I agree that there are not that many great sources out there on the topic for beginners 🤔

I would definitely write a series of articles/an ebook on the topic, however that does not help you at the moment. My suggestion would be to just write your controllers like you are used to, but instead of returning views, you just return a json response, or you can even utilise API resources for easier formatting.

The API resources also give you easy pagination etc.

zerosAndOnes's avatar

@Reached Thanks for taking some time out of your day to answer this. God bless you!

Any chance you can show. me an example code? for instance, if I have a users table and a posts table, and they have a relationship, how would I return the posts that belongs to a certain user?

if I am already authenticated in nuxt, how do I return the posts that belongs to me?

I hope you or someone makes a tutorial on this soon. Even a simple multi user blog will be great.

zerosAndOnes's avatar

@Reached Great, thanks a lot!

And when you get the chance, please do up a full tutorial as well; there might be a lot of people out there that you will do a great favour!

Reached's avatar
<?php

namespace App\Http\Controllers;

php
use App\Models\User;
use Illuminate\Http\Request;

class UserPostController extends Controller
{
    public function index()
    {
        $userPosts = User::with('posts')->get();

        return response()->json(['userPosts' => $userPosts], 200);
    }
}

So the prerequisite for the above code is that you have:

  1. A User model
  2. A Post model
  3. Each User can have many Post
  4. Each Post belongs to a User

In regards to the authentication, that is a separate thing :)

1 like
zerosAndOnes's avatar

@Reached will this automatically know what user that we already have authenticated using sanctum?

Reached's avatar

@cyberkid007 No, if you want to show the posts for the authenticated user, you should do something like this: auth()->user()->posts;

zerosAndOnes's avatar

@Reached so same thing as the web route. interesting!

I'll check this out and see what I can get out of it. Thanks a lot for the help, and keep me posted for when you post your article/video.

Thanks a lot.

1 like

Please or to participate in this conversation.