DEV Community

Cover image for From Zero to Hero: Your First Steps into PHP and Laravel
Vaiber
Vaiber

Posted on • Edited on

From Zero to Hero: Your First Steps into PHP and Laravel

Embarking on the journey of web development can be both thrilling and daunting. With a myriad of languages and frameworks available, choosing where to start is a crucial first step. PHP, a stalwart of server-side scripting, powers a significant portion of the web. When coupled with Laravel, its most popular framework, PHP development becomes an elegant, efficient, and enjoyable experience. This guide will walk you through the foundational steps to get you started with PHP and Laravel, transforming you from a curious beginner to a budding developer ready to build amazing web applications.

The Allure of PHP and Laravel

PHP (Hypertext Preprocessor) has been around for decades, evolving continuously to meet the demands of modern web development. Its widespread adoption means a vast community, extensive documentation, and a wealth of available libraries. Laravel, introduced by Taylor Otwell in 2011, brought a new level of sophistication and developer-friendliness to the PHP ecosystem. It champions expressive syntax, a robust set of tools for common tasks like routing, authentication, and caching, and an architecture (MVC - Model-View-Controller) that promotes well-organized and maintainable code.

Together, PHP and Laravel offer a potent combination for building everything from simple websites to complex enterprise-level applications. Let's dive into setting up your local environment.

A serene, minimalist workspace with a computer screen displaying elegant PHP code, a glowing PHP elephant logo subtly visible. The overall mood is calm and focused, symbolizing a clean development environment for PHP.

Step 1: Setting Up Your PHP Development Environment

Before you can write a single line of PHP code, you need an environment where it can run. PHP is a server-side language, meaning it executes on a web server, not in your browser directly. For local development, you'll simulate this server environment on your own computer.

There are several ways to achieve this:

  • XAMPP: A free and easy-to-install Apache distribution containing MariaDB, PHP, and Perl. It's cross-platform (Windows, macOS, Linux) and excellent for beginners.
  • MAMP: Similar to XAMPP, but originally designed for macOS (though now available for Windows too).
  • WampServer: A Windows-specific web development environment.
  • Docker: A more advanced option using containerization, offering flexibility and isolation but with a steeper learning curve for absolute beginners.

For this tutorial, we'll focus on XAMPP due to its simplicity.

Installing XAMPP:

  1. Download: Visit the Apache Friends website and download the XAMPP installer appropriate for your operating system.
  2. Install: Run the installer. You can generally accept the default components. The key ones you need are Apache (the web server) and PHP.
  3. Launch XAMPP Control Panel: Once installed, open the XAMPP Control Panel.
  4. Start Services: Start the Apache module. If you plan to work with databases soon (which Laravel heavily relies on), start the MySQL module as well. You should see their status turn green.

A clear, friendly, and slightly stylized illustration of the XAMPP control panel. Apache and MySQL modules are highlighted with a green 'running' status indicator. The overall look should be clean and encouraging for a beginner.

Testing Your PHP Installation:

  1. Find your htdocs folder: This is the root directory for your web server. In XAMPP, it's typically located at C:\xampp\htdocs on Windows or /Applications/XAMPP/htdocs on macOS.
  2. Create a test file: Inside htdocs, create a new folder, say myphpproject. Inside myphpproject, create a file named info.php.
  3. Add PHP code: Open info.php in a text editor (like VS Code, Sublime Text, or even Notepad) and add the following PHP code:

    <?php
    phpinfo();
    ?>
    
  4. Access via browser: Open your web browser and navigate to http://localhost/myphpproject/info.php.

If everything is set up correctly, you should see a detailed page displaying information about your PHP installation. Congratulations, PHP is running!

Step 2: PHP Fundamentals - A Quick Dip

Now that PHP is running, let's write a slightly more interactive script.

  • Syntax Basics:

    • PHP code is enclosed in <?php ... ?> tags.
    • Statements end with a semicolon (;).
    • Variables start with a $ sign (e.g., $name = "World";).
    • echo is used to output data to the browser.
  • "Hello, World!" with a variable:
    Modify your info.php file or create a new one, say hello.php in your myphpproject folder, with the following content:

    <?php
    $name = "Developer";
    echo "Hello, " . $name . "!"; // The . operator concatenates strings
    
    echo "<br>"; // HTML line break
    
    $hour = date('H'); // Get current hour in 24-format
    if ($hour < "12") {
        echo "Good Morning!";
    } elseif ($hour < "18") {
        echo "Good Afternoon!";
    } else {
        echo "Good Evening!";
    }
    ?>
    

    Access it via http://localhost/myphpproject/hello.php in your browser. You should see a personalized greeting based on the time of day. This simple script demonstrates variable usage, string concatenation, and a basic conditional statement.

Step 3: Introducing Composer - PHP's Package Manager

Modern PHP development heavily relies on external libraries or "packages" that provide pre-built functionality. Managing these dependencies manually would be a nightmare. Enter Composer, the de facto dependency manager for PHP. Laravel itself, and many of its components, are Composer packages.

Think of Composer as a tool that helps you declare, install, and update the libraries your project needs.

A stylized visual representation of the Composer logo (a conductor's baton and musical notes) with abstract package icons and flowing lines connecting them, symbolizing dependency management. The image should have a modern and tech-savvy feel.

Installing Composer:

  1. Download: Visit the Composer official website.
  2. Installation:
    • Windows: Download and run Composer-Setup.exe. It will usually auto-detect your PHP installation. If not, you'll need to point it to your php.exe file (e.g., C:\xampp\php\php.exe).
    • macOS/Linux: You can install Composer locally or globally by following the command-line instructions on the download page. For simplicity, follow their instructions for a global install, which typically involves downloading the composer.phar and moving it to a directory in your PATH (like /usr/local/bin/composer).
  3. Verify Installation: Open a new terminal or command prompt (important to ensure it picks up PATH changes) and type:

    composer --version
    

    You should see the Composer version printed, confirming it's installed correctly.

Step 4: Installing Laravel

With PHP and Composer ready, installing Laravel is straightforward. Laravel offers an installer tool to quickly scaffold new projects.

  1. Install the Laravel Installer (via Composer):
    Open your terminal or command prompt and run:

    composer global require laravel/installer
    

    This command downloads the Laravel installer and makes it globally available on your system. You might need to ensure your system's Composer vendor/bin directory is in your PATH. Composer usually tells you this location upon successful installation. (e.g., on Windows, it might be C:\Users\YourUser\AppData\Roaming\Composer\vendor\bin. On macOS/Linux, ~/.composer/vendor/bin or ~/.config/composer/vendor/bin).

  2. Create a New Laravel Project:
    Navigate in your terminal to the directory where you want to create your projects (this doesn't have to be XAMPP's htdocs folder, as Laravel has its own built-in development server). Then run:

    laravel new blog
    

    Replace blog with your desired project name. This command will create a new directory named blog (or your chosen name) and download all the necessary Laravel files and dependencies. This might take a few minutes.

A dynamic, slightly isometric view of a command line interface. The command 'laravel new blog' is being typed out, with a stylized Laravel logo appearing faintly in the background or as a watermark. The scene should evoke a sense of creation and new beginnings.

Alternatively, you can create a new Laravel project directly using Composer without the global installer:

   composer create-project --prefer-dist laravel/laravel blog
Enter fullscreen mode Exit fullscreen mode
  1. Project Structure Overview: Once done, cd blog into your new project directory. You'll see a well-organized structure:
    • app/: Core code of your application (Models, Controllers, etc.).
    • bootstrap/: Files that bootstrap the framework.
    • config/: All application configuration files.
    • database/: Database migrations and seeds.
    • public/: The web server's document root, containing the index.php entry point.
    • resources/: Views (HTML templates), raw assets (CSS, JS), and language files.
    • routes/: All route definitions for your application.
    • storage/: Compiled Blade templates, file-based sessions, file caches, and other files generated by the framework.
    • tests/: Automated tests.
    • vendor/: Composer dependencies.

Step 5: Your First Laravel Pages

Laravel comes with a handy development server called Artisan.

  1. Start the Development Server:
    In your terminal, from the root of your Laravel project (blog directory), run:

    php artisan serve
    

    This will typically start a development server on http://127.0.0.1:8000 or http://localhost:8000. Open this address in your browser. You should see the default Laravel welcome page!

  2. Understanding Basic Routing:
    How did that page appear? Laravel uses a system of routes to map URLs to specific actions (like displaying a view or executing controller logic).
    Open routes/web.php. You'll see something like this:

    use Illuminate\Support\Facades\Route;
    
    Route::get('/', function () {
        return view('welcome');
    });
    

    This tells Laravel: "When someone makes a GET request to the root URL (/), execute this function, which returns the welcome view." The welcome view is located in resources/views/welcome.blade.php.

  3. Creating a New Route and View:
    Let's create a new page.

    • Create a view: In resources/views/, create a new file named about.blade.php. The .blade.php extension signifies it's a Blade template (Laravel's powerful templating engine). Add some simple HTML:
        <!DOCTYPE html>
        <html>
        <head>
            <title>About Us</title>
        </head>
        <body>
            <h1>About Our Awesome Company</h1>
            <p>This is the about page for our new Laravel application.</p>
            <p>Today's message is: {{ $message }}</p>
        </body>
        </html>
Enter fullscreen mode Exit fullscreen mode
    Notice `{{ $message }}`. This is Blade syntax for echoing a variable.  

*   **Define the route:** In `routes/web.php`, add a new route:
Enter fullscreen mode Exit fullscreen mode
        Route::get('/about', function () {
            $info = "Learning Laravel is fun!";
            return view('about', ['message' => $info]);
        });
Enter fullscreen mode Exit fullscreen mode
    This route maps the /about URL. We're also passing a variable $info (as message) to our about view.

Now, navigate to http://localhost:8000/about in your browser. You should see your new "About Us" page with the message displayed!

Enter fullscreen mode Exit fullscreen mode




Step 6: Understanding the MVC Pattern in Laravel

While you can put logic directly into route closures (as we just did), for larger applications, this becomes messy. Laravel encourages the use of the Model-View-Controller (MVC) architectural pattern.

An abstract representation of the MVC (Model-View-Controller) architecture. Perhaps three interconnected, stylized blocks or orbs labeled 'M', 'V', and 'C', with arrows showing the flow of data and logic. The colors should be harmonious and the design clean, suggesting an organized structure.

  • Model: Represents your data and business logic. Interacts with the database. (e.g., a User model might interact with a users table).
  • View: The presentation layer; what the user sees (e.g., HTML templates - our Blade files).
  • Controller: Handles user input, interacts with the Model, and selects a View to render. It's the intermediary.

Let's refactor our /about page to use a controller.

  1. Create a Controller:
    Use Artisan to generate a controller. In your terminal:

    php artisan make:controller PageController
    

    This creates PageController.php inside app/Http/Controllers/.

  2. Add a Method to the Controller:
    Open app/Http/Controllers/PageController.php and add a method:

    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    
    class PageController extends Controller
    {
        public function about()
        {
            $info = "Learning Laravel with Controllers is even more fun!";
            return view('about', ['message' => $info]);
        }
    }
    
  3. Update the Route:
    Modify your /about route in routes/web.php to point to this controller method:

    use App\Http\Controllers\PageController; // Add this at the top
    
    // ... other routes ...
    
    Route::get('/about', [PageController::class, 'about']);
    

    Now, if you refresh http://localhost:8000/about, it should still work, but the logic is now neatly organized in PageController. This separation of concerns is key to building scalable applications.

Step 7: Next Steps and Further Learning

You've taken your first significant steps into the world of PHP and Laravel! This is just the beginning of an exciting journey. Here are some areas you'll want to explore next:

  • Databases and Eloquent ORM: Laravel's Eloquent ORM makes interacting with databases incredibly intuitive. Learn about migrations (to define your database schema), models, and querying.
  • Blade Templating In-Depth: Explore layouts, components, directives, and control structures within Blade to create dynamic and reusable views.
  • Forms and Validation: Handling user input securely and validating data is crucial for any web application.
  • Authentication and Authorization: Laravel provides robust systems for user registration, login, and managing permissions.
  • Frontend Scaffolding: Laravel offers starter kits like Breeze or Jetstream to quickly set up frontend frameworks like Vue.js or React, along with Tailwind CSS.
  • Artisan Commands: Get familiar with more Artisan commands for tasks like creating models, migrations, seeders, and more.

Resources for Continued Learning:

Conclusion: Your Journey Has Just Begun

Setting up PHP and Laravel, and understanding their basic concepts, lays a solid foundation for your web development aspirations. The initial learning curve can feel steep, but the power and elegance of Laravel quickly become apparent. Remember that consistency and practice are key. Build small projects, experiment with different features, and don't be afraid to consult the documentation or community resources when you get stuck.

The path from "Hello, World!" to deploying complex web applications is paved with continuous learning and discovery. With PHP and Laravel as your tools, you're well-equipped for that journey. Happy coding!

#emerging-technologies

Top comments (0)