Skip to main content

Posts

Using PHP Traits for Laravel Eloquent Relationships

  I recently began refactoring a bunch of code on a project and found myself putting the same methods on my Eloquent models for a relation to an Account class. FYI I prefer to have getters and setters rather than accessing properties magically. So lets say we have a Post model that looks something like this: <?php namespace App; use Illuminate\Database\Eloquent\Model; /** * Class Post * * @package App */ class Post extends Model { /** * @return string */ public function getTitle() { return $this->getAttribute('title'); } /** * @param string $title * @return $this */ public function setTitle(string $title) { $this->setAttribute('title', $title); return $this; } /** * @return string */ public function getPost() { return $this->getAttribute('post'); } /** * @param string $post * @return $this */ public function se...

How to build a Laravel REST API with Test-Driven Development

There is a famous quote by   James Grenning, one of the pioneers in TDD and Agile development methodologies: If you’re not doing test-driven development, you’re doing debug-later development - James Grenning Today we’ll be going on a Laravel journey driven by tests. We’ll create a Laravel REST API complete with authentication and CRUD functionality without opening Postman or a browser. 😲 Note:   This walkthrough assumes that you understand the basic concepts of   Laravel   and   PHPUnit . If you’ve got that out of the way? Let’s drive. Setting up the project Start by creating a new Laravel project with   composer create-project --prefer-dist laravel/laravel tdd-journey . Next, we need to run the authentication scaffolder that we would use, go ahead and run   php artisan make:auth   then   php artisan migrate . We will not actually be using the routes and views generated. For this project, we would be using   jwt-auth . So go ahead and ...