Laravel: The good, better, and awesome

Adam French
6 min readAug 26, 2018

--

I just started learning the PHP framework Laravel, and I’m very impressed. I’d never contemplated using PHP or Laravel, but after hearing Zachary Schuessler rave about the framework, I decided to give it a shot. This article is about some of Laravel’s capabilities, and why it’s objectively awesome.

What is Laravel?

As it mentions in the documentation, Laravel is “The PHP Framework For Web Artisans”. It is a powerfully simple tool to develop just about anything, from REST API’s, to full stack progressive web apps (buzzword alert). It’s core features include routing configuration, complete pre-made scaffolding for authentication/mailing/asset compilation/testing, and a rich database management system with Eloquent ORM and Query Builder. Before learning the framework, I had very minimal experience with anything related with the backend. Laravel really eased the learning curve as a frontend dev going into the realm of PHP and the database.

The Features

Laravel is such an incredibly feature-rich framework that I could spend many months sampling and writing about every feature it has to offer. In this article, I’ll only highlight the features that I personally found useful in learning how to code on the backend.

Scaffolding

When you are finished installing and configuring Laravel, it’s an extremely simple process to get an app with authentication up and running.

Tip: Here’s a great video to help you get everything installed and configured for a smooth development experience

After you get everything set up, go ahead and type in php artisan make:auth . This simple command automatically adds all the routes, views, and controllers necessary for users to login and out of you app.

While most will end up modifying the initial authentication structure, it’s easy to overwrite! For instance, to change the registration controller’s validation view:

class RegisterController extends Controller{/*|--------------------------------------------------------------------------| Register Controller|--------------------------------------------------------------------------|| This controller handles the registration of new users as well as their| validation and creation. By default this controller uses a trait to| provide this functionality without requiring any additional code.|*/use RegistersUsers;...
}

see that use RegistersUsers line? That’s a trait, a php feature that Laravel leverages effectively to modularize the framework. You can override trait functionality by writing the function you want to change in the class that uses that trait. Here we want to override showRegistrationForm() and make it return a different view:

trait RegistersUsers{use RedirectsUsers;/*** Show the application registration form depending on which role the user has.** @return \Illuminate\Http\Response*/
// Copy and paste this function in the Register Controller to override
public function showRegistrationForm() {return view('auth.register');}

Pretty cool, right? This is only a tiny part of all the functionality that comes out of the box. There’s helpful boilerplate for a mailing service, caching, filesystem, and much more.

Tip: It’s best practice that you never touch the actual vendor code (like the RegistersUsers trait). It could cause bugs if you update to a new version. Instead, copy and paste the function you’d like to override.

Dependency Injection

Dependency injection is a common theme that the framework uses to enable a speedy development experience. It’s common to use it with controllers, routes, and service providers. Here’s an example of how dependency injection and type hinting can be used to create clear, clean code:

Let’s say I want to access a user’s task in the database. I would want the route to look something like : Route::get(‘/tasks/{task}’,‘TaskController@show’);

See that {task} parameter? It gets injected into the referenced function. In this case it might look like this:

// Json encode data for use in task-detail vue componentpublic function show(Task $task) {$jsonTask = json_encode($task);$comments = json_encode($task->comments()->get());return view('tasks.detail',compact('jsonTask','comments'));}

I’ll let the docs explain how this works:

“Since the $task variable is type-hinted as the App\Task Eloquent model and the variable name matches the {task} URI segment, Laravel will automatically inject the model instance that has an ID matching the corresponding value from the request URI. If a matching model instance is not found in the database, a 404 HTTP response will automatically be generated.”

So, type hint the parameter, match it with the URI segment in your route, and you’ll access the referenced model (if it exists)without parsing or calling functions! Pretty sweet.

Dependency Injection (DI) is a great tool to have in your belt as a developer. Pay attention to all the use cases inside Laravel! You’ll definitely learn how to leverage DI moving forward.

Eloquent ORM, Database Migrations, and Query Builder

So far, these features are what have made Laravel so easy to learn for me. To start, I’ll go over the Eloquent ORM (object/relational mapper). It allows you to create and connect objects and their relationships in PHP and the database with ease. Check out this example using a simple Task object:

Tip: Refer to this documentation if you haven’t gotten your database connection set up yet, you’ll need to do that first.

First you create the model by typing php artisan make:model Task in your console. You can also create a DB migration for the Task model by adding a --m at the end of the command. This will create the following boilerplate:

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Task extends Model{//}

If you added the -m flag, you’ll see a create_tasks_table object with a timestamp in front of it show up in the database/migrations folder:

Tip: I usually use the -m flag when creating a model, or you have to create the below code manually.

<?phpuse Illuminate\Support\Facades\Schema;use Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration;class CreateTasksTable extends Migration{/*** Run the migrations.** @return void*/public function up(){
//here's where you add properties to an object
Schema
::create('tasks', function (Blueprint $table) {
$table->increments('id');$table->timestamps();
$table->string('name');
$table->string('description');
});}/*** Reverse the migrations.** @return void*/public function down(){Schema::dropIfExists('tasks');}}

Now you have the scaffolding to begin adding properties to your models. All you have to do is add columns to the table in the Schema::create function like this:

$table->string('name');

Now that you’ve set up the model and corresponding migration in code, we can set up the actual tables and columns in the database by running the migration Type php artisan migrate and check your database. You should find a tasks table waiting for fresh data 😎.

Now that you have a model set up, it’s time to start thinking about relationships… maybe to a User object. Check out the documentation for a breakdown of how relationships work in Eloquent.

After you get the models and database tables up and running, it’s time to start performing queries to show data on the frontend. Most of the time, queries of like this are performed within controllers. You can do this through the Eloquent ORM, raw SQL code, or the fluent query builder. Laravel’s various query interfaces support these DB’s:

  • MySQL
  • PostgreSQL
  • SQLite
  • SQL Server

So, let’s write a query! Let’s say I want to get all the tasks in my database, sort them in alphabetical order, and return a view with the data from the query. I like using Eloquent to conduct my queries so it will look like this:

Tip: It isn’t best practice to put queries in the controller like this, but i’m doing it for this minimal example. For more complex use cases, It’s good to use the repository pattern and query scopes to manage your queries.

// remember to include the model! 
use App\Task;
class TasksController extends Controller{public function __construct(){}public function index() {//Here's where the magic happens!
$tasks = App\Task::all()->orderBy('name','desc')->get();
return view('tasks.index',compact('tasks'));}

When I found out interacting with the database was this simple (well, after you set up routes, models, and migrations), I was pretty hyped. Of course, this is an extremely simple use case, but for those just getting started will be the first type of queries.

So that’s a very simple introduction to Laravel! I recommend that any programmer that has wanted to get into the backend but doesn’t know where to start try this, because it made the process much more simple for me. It also has more advanced features for complex applications and experienced devs. The documentation, budding community, and constant improvement are three other great reasons to give it a shot.

I hope this article helped (if it did, a 👏 or two would mean a lot). If there’s anything you’d like to see in the future or thought was missing from this intro, please comment or message me, I’d love to hear your thoughts.

Happy coding!

More where this came from

This story is published in Noteworthy, where thousands come every day to learn about the people & ideas shaping the products we love.

Follow our publication to see more product & design stories featured by the Journal team.

--

--

Adam French

Regenerative Design + Entrepreneurship + Personal Development & Spirituality. Want to jam? Hit me up adam@interform.space