Currently Available: Need a skilled Software Developer for your next project?
Categories
Laravel

PHP Concepts You Need Before Learning Laravel

Laravel gives you conventions and tools for building web applications, and PHP is the language those tools run on. Before you start learning Laravel, get comfortable reading PHP functions, arrays, classes, and namespaces. You don't need advanced PHP expertise, because knowing these basics is enough to follow Laravel's routes, controllers, and models.

PHP supports type declarations, though it doesn't require you to declare a type for every variable. Laravel builds on that flexibility and adds its own behavior, such as routing requests and automatically supplying objects to controller methods. Where version-specific details matter, the examples below use Laravel 13, which requires PHP 8.3 or newer according to its deployment requirements.

PHP values, arrays, and comparisons

PHP variables hold values like strings, integers, and booleans. You can also declare the types a function expects and the type it returns:

function greet(string $name): string
{
    return "Hello, $name";
}

Here, string sets the type for both the parameter and the return value. In some cases, PHP converts basic values, such as numbers, strings, and true/false values, to another type automatically. PHP calls this coercion, so a type declaration does not always enforce an exact match. If you add declare(strict_types=1) to a file, PHP enforces strict scalar checks instead. Learn to recognize type declarations, and check a project's settings before you assume how PHP will handle a value with the wrong type. The PHP type documentation covers both declarations and strict typing.

PHP arrays work as both ordered lists and key-value maps. Laravel uses them to pass collections of values, such as configuration options or data for a view. Write a numeric list when order matters, and use named keys when each value has a distinct meaning:

$colors = ['blue', 'green'];
$user = ['name' => 'Sam', 'active' => true];

You also need to know the difference between == and ===. When you use ==, PHP may convert types before it compares the values. When you use ===, PHP requires both the value and the type to match. Choose strict comparison for predictable checks, and use loose comparison only when you want PHP to convert types:

'5' === 5; // false
'5' == 5;  // true

That distinction matters when your code handles request data, because a value coming from outside the application may arrive as a string even when it looks like a number. PHP documents these rules in its guides to arrays and comparison operators.

Functions and closures

A function groups code under a name, accepts inputs through parameters, and can return a result. Laravel uses functions and methods throughout its codebase, including in route definitions. A closure is an anonymous function that you can pass around like any other value:

$message = 'Welcome';

$handler = function () use ($message) {
    return $message;
};

The use clause makes the outer variable available inside the closure so the function can read it. Laravel route callbacks use this same PHP feature:

Route::get('/status', function () {
    return 'OK';
});

That callback is ordinary PHP syntax, and Laravel runs it whenever an incoming request matches the route. Make sure you understand how parameters, return values, and variable scope work before you rely on the framework to handle them for you. PHP's function documentation and anonymous-function reference explain these language features in detail.

Classes, objects, and constructors

A class describes the data (properties) and actions (methods) that its objects have. A method is a function declared inside a class, and a constructor is a special method that PHP runs when it creates a new object. Visibility keywords control where code can access a property or method. Marking one public allows access from anywhere, while marking it private restricts access to the class itself.

class Report
{
    public function __construct(
        private string $title
    ) {}

    public function title(): string
    {
        return $this->title;
    }
}

In Laravel, controllers and Eloquent models are PHP classes. An Eloquent model extends Laravel's base Model class, and Laravel applies conventions on top of it, such as deriving the database table name from the model name. You don't need to master every object-oriented feature before you start, but you should be able to read a constructor, follow a method call, and recognize inheritance. The PHP classes reference and Laravel's Eloquent introduction show these ideas in context.

Namespaces and Composer autoloading

A namespace gives a class a full name so two classes with the same short name do not clash. You can use the use keyword to import a class and refer to it more concisely:

namespace App\Http\Controllers;

use App\Services\ReportService;

class ReportController
{
    public function __construct(
        private ReportService $reports
    ) {}
}

Composer is PHP's tool for managing dependencies like libraries, and it also loads class files automatically. Under its PSR-4 convention, Composer maps a namespace prefix to a directory, then maps the rest of the class name to folders and a file. Composer generates an autoloader so PHP can load those classes without you manually requiring each file. That is why Laravel code can refer to a namespaced class through an import instead of spelling out its file path. See PHP's namespace rules and the PSR-4 autoloading standard for the full details.

Injected dependencies and exceptions

A class often depends on another object to do its work. When you use constructor injection, you pass that object into the class instead of creating it inside the class. In the ReportController example above, the controller receives a ReportService object through its constructor.

Laravel's service container can create and supply many concrete classes on its own. That automatic resolution comes from Laravel, while the constructor and type declaration are standard PHP. If a dependency is an interface (a type that specifies which methods a class must provide) or needs custom setup, you may need to add a binding that tells Laravel's container which class to supply. The service container documentation explains how Laravel resolves dependencies.

PHP uses exceptions to represent failures that interrupt normal execution. You put code that might throw an exception inside a try block, and you handle a matching exception in a catch block:

try {
    $result = performTask();
} catch (RuntimeException $exception) {
    // Handle this specific failure.
}

Handle exceptions where your code can make a meaningful decision, such as returning an appropriate response or recording useful details. If you catch every possible error without a plan, you can hide programming mistakes. PHP's try and catch reference explains how exceptions move through function calls.

Web requests, responses, and input

A web request carries information from a client, such as a browser, to a server, and a response carries the server's result back. Laravel routes connect an incoming request to code that returns a response, often through a controller.

Treat request values as external input. When you cast a value to another type, you change how PHP interprets it, but you do not prove that the value follows your application's rules. If you convert text to an integer, for example, you still haven't established that the number is allowed for a particular operation. Laravel's request documentation describes ways to read and cast input, and you should validate that input against your feature's rules before your code acts on it.

When you display user-provided text in a Blade template (a file that defines a page's HTML), use escaped output such as {{ $value }}. Blade escapes this output by default, which helps prevent browsers from interpreting the text as executable HTML. The {!! $value !!} syntax outputs unescaped content, so use it only when you trust the content and have handled the security implications. Laravel explains this behavior in its Blade documentation.

When you are ready to start Laravel

You are ready to begin Laravel once you can trace a value through a function, explain what an array contains, read a class constructor, and follow a namespaced class through an import. You should also recognize how Laravel adds behavior around ordinary PHP features: a route runs a PHP callback, the container supplies typed dependencies, and Eloquent adds database conventions to PHP model classes.

You can learn deeper PHP topics alongside Laravel. Read the framework's examples carefully, and pause to check a PHP feature whenever its behavior is unclear.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *