DEV Community

loading...
IT Minds

Single Page Application API from Laravel

simmetopia profile image Simon Bundgaard-Egeberg Originally published at insights.it-minds.dk ・3 min read

KnitZilla, the backend(ening);

In my last episode, I wrote about how I got a typescript react app to work in a Laravel stack.

In this episode, I will try to explain why I think Laravel is a cool framework, and why you might want to use it for your next full-stack project!

First of all, let's look at the model.
Laravel provides a Database agnostic tool to write your database migrations in.
For me, being mostly a frontend developer, I wrote my entire database configuration in my first migration, but you might want to do it differently.

What is cool for me, is that I do not need to know the specifics of the underlying database, I just need to maintain a higher-order overview of the model I want in my app.

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('projects', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')
                  ->references('id')
                  ->on('users')
                  ->onDelete("cascade");
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

And thus, my database is created. I like it! Notice that I am adding a foreign key reference to a user model in this model.

As a developer, after having created the actual persistence model we need to find a way to query our data. Again, Laravel provides an easy to use interface for such options.

class Project extends Model
{
    //
    protected $fillable = [
        "name", "user_id"
    ];
    public function user()
    {
        return $this->belongsTo("App\User");
    }
    public function counters()
    {
        return $this->hasMany("App\Counter");
    }
}

With Eloquent https://laravel.com/docs/6.x/eloquent, we can tell the relations and which fields should be mutable through the model(the $fillable field). And thus, our query system is in place.

USE IT!

How do we then go about using it?
Well in a controller dummy!.

class ProjectController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:api');
    }

    public function index()
    {
        return response(Project::with("user")
                        ->where("id", Auth::user()->id)
                        ->first());
    }

    public function store(Request $request)
    {
        $userId = Auth::user()->id;
        //
        $name = $request->input("name");
        $project = Project::create([
            "user_id" => $userId,
            "name" => $name
        ]);
        return response($project, 200);
    }
}

First of all, I love how I can add which middleware chain I want to use in the constructor, and it then applies to all routes in this controller.

In the index function, which will be exposed as the get request at the root of this controller will use our eloquent data model.

Since I am using authentication in this controller, I can pull out the id of the user who made the request and then only return the projects associated with that user (In the Project eloquent model I specified a user's function).

Looking closer at the fluent API query I made, the first function chained is called with("user"). This is how you can lazy load values on the request to the database, saving precious roundtrips. The next to parts is pretty self-explanatory.

Later, in the store function (which would map to the POST request of the root) I create a new project resource. And again leveraging that I have the current user through the context, I can safely say that it is this user that I want to add the project on.

This is just the API part of Laravel, and there are so many more cool things that you can do.

To just name a few:

  1. Cron jobs baked in (Task scheduling)
  2. Different middleware groups to different endpoints
  3. Full app expectation tracking
  4. Broadcasting

In summary, using Laravel and React has allowed me, in a very short amount of time, to create a full-stack app, where users can sign up and log in. All endpoints but authentication endpoints are protected, and the data is persisted (in my case in a MySQL database).

Discussion

pic
Editor guide