Tutorial: Building a Laravel 9 Real Estate Listing App

Avatar

By squashlabs, Last Updated: October 23, 2023

Tutorial: Building a Laravel 9 Real Estate Listing App

Setting Up the Development Environment

To get started with building a Laravel 9 real estate listing app, we need to set up our development environment. Here are the steps to follow:

1. Install PHP: Laravel is a PHP framework, so we need to have PHP installed on our system. You can download the latest version of PHP from the official website and follow the installation instructions for your operating system.

2. Install Composer: Composer is a dependency management tool for PHP. It is used to install Laravel and its dependencies. You can download Composer from the official website and follow the installation instructions for your operating system.

3. Install Laravel: Once Composer is installed, we can use it to install Laravel. Open a terminal or command prompt and run the following command:

composer global require laravel/installer

This will install the Laravel installer globally on your system.

4. Create a New Laravel Project: Now, we can create a new Laravel project. Navigate to the directory where you want to create the project and run the following command:

laravel new real-estate-app

This will create a new Laravel project named “real-estate-app” in the current directory.

5. Start the Development Server: Once the project is created, navigate to its directory and start the development server by running the following command:

php artisan serve

This will start the development server at http://localhost:8000.

Related Article: Installing Docker on Ubuntu in No Time: a Step-by-Step Guide

Creating the Laravel Project

In this chapter, we will explore the structure of the Laravel project and understand its components. Let’s dive in:

1. Directory Structure: When you create a new Laravel project, it generates a default directory structure. The most important directories are:
app: Contains the core application code, including models, controllers, and views.
config: Contains configuration files for various Laravel components.
database: Contains database-related files, such as migrations and seeders.
public: Contains the publicly accessible files, including the index.php file that serves as the entry point for the application.
resources: Contains assets like views, CSS, and JavaScript files.
routes: Contains the route definitions for the application.
tests: Contains test cases for the application.

2. Routes: Laravel uses a routing system to handle incoming HTTP requests. The routes are defined in the routes/web.php file. You can define routes for different HTTP methods and URLs, and map them to controller methods or closures. For example:

Route::get('/listings', 'ListingController@index');
Route::post('/listings', 'ListingController@store');

3. Controllers: Controllers handle the logic for processing HTTP requests and generating responses. They are stored in the app/Http/Controllers directory. You can create a new controller using the make:controller Artisan command. For example, to create a ListingController, run the following command:

php artisan make:controller ListingController

4. Models: Models represent database tables and handle interactions with the database. They are stored in the app/Models directory. You can create a new model using the make:model Artisan command. For example, to create a Listing model, run the following command:

php artisan make:model Listing

5. Views: Views are responsible for displaying the HTML content of your application. They are stored in the resources/views directory. Laravel uses the Blade templating engine to provide a clean syntax for writing views. You can create a new view file with the .blade.php extension. For example, to create a view for listing details, create a file named show.blade.php in the resources/views/listings directory.

Designing the Database Schema

A well-designed database schema is crucial for a real estate listing app. In this chapter, we will design the schema and create the necessary database migrations. Let’s get started:

1. Define the Entities: Before designing the database schema, we need to identify the entities involved in our app. In a real estate listing app, common entities include listings, users, and images. Create a list of the entities and their attributes.

2. Create Migrations: Laravel provides a convenient way to create and manage database migrations. Migrations allow us to version control the changes to the database schema. To create a new migration, run the following command:

php artisan make:migration create_listings_table --create=listings

This will generate a new migration file in the database/migrations directory. Open the migration file and define the table structure using the Schema builder. For example:

public function up()
{
    Schema::create('listings', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('description');
        $table->integer('price');
        $table->timestamps();
    });
}

3. Run Migrations: Once the migration is defined, we can run it to create the corresponding database table. Run the following command to run all pending migrations:

php artisan migrate

This will execute the migration and create the listings table in the database.

4. Repeat the above steps for other entities in your app, such as users and images. Create separate migration files for each table and define the table structure accordingly.

Implementing User Authentication

User authentication is an essential feature of any web application. In this chapter, we will implement user authentication using Laravel’s built-in authentication system. Let’s proceed:

1. Generate Authentication Scaffolding: Laravel provides a convenient way to generate the necessary authentication views and routes. Run the following command to generate the authentication scaffolding:

php artisan make:auth

This command will create the necessary views, controllers, and routes for user registration, login, and password reset.

2. Configure Database Connection: Before we can use the authentication system, we need to configure the database connection in the .env file. Open the .env file and update the database credentials according to your environment.

3. Run Migrations: Next, we need to run the migrations to create the necessary tables for authentication. Run the following command to run the migrations:

php artisan migrate

This will execute the migration and create the required tables, such as users and password_resets.

4. Test Authentication: With the authentication scaffolding in place, we can now test the user registration and login functionality. Visit the registration page at http://localhost:8000/register and create a new user account. You can then log in using the created credentials.

5. Customize Authentication Views (Optional): If you want to customize the authentication views, you can modify the Blade templates located in the resources/views/auth directory. Laravels’ documentation provides detailed information on how to customize the views to match your application’s design.

Related Article: How to Install and Use Docker

Building the Real Estate Listing Model

In this chapter, we will focus on building the Listing model, which represents real estate listings in our application. Let’s proceed with the following steps:

1. Create the Model: Run the following command to create the Listing model:

php artisan make:model Listing

This will generate a new model file named Listing.php in the app/Models directory.

2. Define the Model Properties: Open the Listing.php file and define the properties of the Listing model. These properties should correspond to the columns in the listings table. For example:

protected $fillable = [
    'title', 'description', 'price'
];

3. Define Relationships: If your real estate listing app has relationships with other entities, such as users or images, you can define those relationships in the Listing model. For example, to define a one-to-many relationship between listings and users, add the following method to the Listing model:

public function user()
{
    return $this->belongsTo(User::class);
}

4. Define Additional Methods: Depending on the requirements of your app, you can define additional methods in the Listing model. These methods can encapsulate complex logic or provide convenient functionalities. For example, you can define a method to retrieve the formatted price of a listing:

public function formattedPrice()
{
    return '$' . number_format($this->price, 2);
}

Creating the Listing CRUD Operations

In this chapter, we will implement the CRUD (Create, Read, Update, Delete) operations for the real estate listings. Let’s proceed with the following steps:

1. Create the ListingController: Run the following command to create the ListingController:

php artisan make:controller ListingController --resource --model=Listing

This will generate a new controller file named ListingController.php in the app/Http/Controllers directory. The --resource option tells Laravel to generate the controller with resourceful methods, while the --model option associates the controller with the Listing model.

2. Implement Index Method: Open the ListingController.php file and implement the index method. This method should retrieve all the listings from the database and pass them to the corresponding view. For example:

public function index()
{
    $listings = Listing::all();
    return view('listings.index', compact('listings'));
}

3. Implement Create Method: Add the following method to the ListingController.php file to show the form for creating a new listing:

public function create()
{
    return view('listings.create');
}

4. Implement Store Method: Add the following method to the ListingController.php file to handle the submission of the create listing form:

public function store(Request $request)
{
    $listing = Listing::create($request->all());
    return redirect()->route('listings.show', $listing);
}

5. Implement Show Method: Add the following method to the ListingController.php file to show the details of a listing:

public function show(Listing $listing)
{
    return view('listings.show', compact('listing'));
}

6. Implement Edit Method: Add the following method to the ListingController.php file to show the form for editing a listing:

public function edit(Listing $listing)
{
    return view('listings.edit', compact('listing'));
}

7. Implement Update Method: Add the following method to the ListingController.php file to handle the submission of the update listing form:

public function update(Request $request, Listing $listing)
{
    $listing->update($request->all());
    return redirect()->route('listings.show', $listing);
}

8. Implement Destroy Method: Add the following method to the ListingController.php file to delete a listing:

public function destroy(Listing $listing)
{
    $listing->delete();
    return redirect()->route('listings.index');
}

9. Define Routes: Open the routes/web.php file and define the routes for the ListingController methods. For example:

Route::resource('listings', ListingController::class);

10. Test the CRUD Operations: With the routes and controller methods in place, you can now test the CRUD operations for the real estate listings. Visit the URLs for each operation and verify that the functionality works as expected.

Implementing Search Functionality

In this chapter, we will add search functionality to our real estate listing app. Users will be able to search for listings based on specific criteria. Let’s proceed with the following steps:

1. Add Search Form: First, we need to create a search form where users can enter their search criteria. Open the view file where you want to display the search form (e.g., resources/views/listings/index.blade.php) and add the following HTML code:


    
    <button type="submit">Search</button>

2. Implement Search Method: Open the ListingController.php file and add the following method to handle the search functionality:

public function search(Request $request)
{
    $query = $request->input('query');
    $listings = Listing::where('title', 'like', "%$query%")
                        ->orWhere('description', 'like', "%$query%")
                        ->get();
    return view('listings.index', compact('listings'));
}

3. Define Search Route: Open the routes/web.php file and define a new route for the search functionality:

Route::get('listings/search', [ListingController::class, 'search'])->name('listings.search');

4. Test the Search Functionality: With the search form and controller method in place, you can now test the search functionality. Enter a search query in the search form and submit it. The app should display the listings that match the search criteria.

Related Article: How To Make A Redirect In PHP

Integrating Vue.js for Dynamic UI

In this chapter, we will integrate Vue.js into our real estate listing app to create a dynamic user interface. Vue.js is a popular JavaScript framework for building reactive web interfaces. Let’s proceed with the following steps:

1. Install Vue.js: Laravel provides built-in support for Vue.js. Run the following command to install Vue.js and its dependencies:

npm install && npm run dev

This will install the necessary dependencies and compile the assets.

2. Create a Vue Component: Open the resources/js/components directory and create a new Vue component file (e.g., Listings.vue). In this file, define the structure and behavior of the Vue component. For example:


    <div>
        <ul>
            <li>
                {{ listing.title }}
            </li>
        </ul>
    </div>



export default {
    data() {
        return {
            listings: []
        };
    },
    mounted() {
        // Fetch listings from the server and assign them to the "listings" data property
        axios.get('/api/listings')
            .then(response => {
                this.listings = response.data;
            })
            .catch(error => {
                console.error(error);
            });
    }
};

3. Register the Vue Component: Open the resources/js/app.js file and register the Vue component by adding the following code:

import Listings from './components/Listings.vue';

Vue.component('listings', Listings);

4. Use the Vue Component: Open the view file where you want to use the Vue component (e.g., resources/views/listings/index.blade.php) and add the following HTML code to include the component:


5. Compile the Assets: Run the following command to compile the assets and make the Vue component available in the app:

npm run dev

6. Test the Dynamic UI: With the Vue component integrated, you can now test the dynamic UI functionality. Load the page that includes the Vue component and verify that the listings are displayed dynamically.

Styling the App with Bootstrap

In this chapter, we will use Bootstrap to style our real estate listing app. Bootstrap is a popular CSS framework that provides pre-designed components and utilities. Let’s proceed with the following steps:

1. Install Bootstrap: Laravel provides built-in support for Bootstrap. Run the following command to install Bootstrap and its dependencies:

npm install && npm run dev

This will install the necessary dependencies and compile the assets.

2. Include Bootstrap CSS: Open the resources/sass/app.scss file and import the Bootstrap CSS by adding the following line at the top:

@import '~bootstrap/scss/bootstrap';

3. Customize the Styles (Optional): If you want to customize the styles, you can modify the app.scss file or create additional SCSS files. You can also override the default Bootstrap variables to customize the theme.

4. Include Bootstrap JavaScript: Open the resources/js/bootstrap.js file and uncomment the following line to include the Bootstrap JavaScript:

// require('bootstrap');

5. Compile the Assets: Run the following command to compile the assets with the Bootstrap styling:

npm run dev

6. Test the Styling: With Bootstrap included, you can now test the styling of your real estate listing app. Load the app in the browser and verify that the Bootstrap styles are applied.

Adding Image Upload Functionality

In this chapter, we will add image upload functionality to our real estate listing app. Users will be able to upload images for their listings. Let’s proceed with the following steps:

1. Update the Database Schema: Open the migration file for the listings table (e.g., database/migrations/2022_01_01_000000_create_listings_table.php) and add a new column for storing the image path:

$table->string('image')->nullable();

2. Run Migrations: Run the following command to run the migrations and update the listings table:

php artisan migrate

3. Update the Listing Model: Open the Listing.php model file and add the image column to the $fillable property:

protected $fillable = [
    'title', 'description', 'price', 'image'
];

4. Add an Image Upload Field: Open the view file where you want to include the image upload field (e.g., resources/views/listings/create.blade.php) and add the following HTML code:

<div class="form-group">
    <label for="image">Image</label>
    
</div>

5. Handle Image Upload: Open the ListingController.php file and update the store and update methods to handle the image upload. Add the following code to the beginning of both methods:

if ($request->hasFile('image')) {
    $imagePath = $request->file('image')->store('public/images');
    $listing->image = $imagePath;
}

6. Display the Image: Open the view file where you want to display the image (e.g., resources/views/listings/show.blade.php) and add the following code to display the image:

@if ($listing->image)
    <img>image) }}" alt="Listing Image" class="img-fluid">
@endif

7. Test the Image Upload: With the image upload functionality implemented, you can now test uploading images for the real estate listings. Create or update a listing with an image and verify that the image is displayed correctly.

Related Article: PHP Date and Time Tutorial

Implementing Pagination

In this chapter, we will implement pagination for the real estate listings. Pagination allows us to split the listings into multiple pages for easier navigation. Let’s proceed with the following steps:

1. Update the Index Method: Open the ListingController.php file and update the index method to paginate the listings. Replace the existing code with the following:

public function index()
{
    $listings = Listing::paginate(10);
    return view('listings.index', compact('listings'));
}

2. Update the Listings View: Open the view file that displays the listings (e.g., resources/views/listings/index.blade.php) and add the following code to display the pagination links:

{{ $listings->links() }}

3. Test the Pagination: With the pagination implemented, load the page that displays the listings and verify that the pagination links are displayed. Click on the pagination links and verify that the listings are split into multiple pages.

Deploying the App with Docker

In this chapter, we will deploy our real estate listing app using Docker. Docker allows us to package the app and its dependencies into containers, making it easier to deploy and manage. Let’s proceed with the following steps:

1. Install Docker: If you haven’t already, install Docker on your development machine. You can download Docker from the official website and follow the installation instructions for your operating system.

2. Create a Dockerfile: In the root directory of your Laravel project, create a new file named Dockerfile. Add the following content to the file:

# Use the official PHP image as the base image
FROM php:8.0-apache

# Set the working directory
WORKDIR /var/www/html

# Install system dependencies
RUN apt-get update && apt-get install -y \
    libpng-dev \
    libjpeg-dev \
    libonig-dev \
    libxml2-dev \
    zip \
    unzip

# Install PHP extensions
RUN docker-php-ext-configure gd --with-jpeg
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd

# Enable Apache rewrite module
RUN a2enmod rewrite

# Copy composer.lock and composer.json
COPY composer.lock composer.json ./

# Install composer dependencies
RUN composer install --no-scripts --no-autoloader

# Copy existing application directory contents
COPY . .

# Generate the optimized autoload files
RUN composer dump-autoload --optimize

# Set recommended PHP.ini settings
RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"

# Change ownership of the application directory
RUN chown -R www-data:www-data .

# Expose port 80 and start the Apache server
EXPOSE 80
CMD ["apache2-foreground"]

3. Create a docker-compose.yml File: In the root directory of your Laravel project, create a new file named docker-compose.yml. Add the following content to the file:

version: '3'
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - 8000:80
    volumes:
      - .:/var/www/html
    depends_on:
      - db
  db:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: secret
      MYSQL_DATABASE: laravel
      MYSQL_USER: laravel
      MYSQL_PASSWORD: secret
    volumes:
      - db_data:/var/lib/mysql
volumes:
  db_data:

4. Build and Run the Docker Containers: Open a terminal or command prompt, navigate to the root directory of your Laravel project, and run the following command to build and run the Docker containers:

docker-compose up -d

5. Test the Deployed App: With the Docker containers running, visit http://localhost:8000 in your browser to access the deployed real estate listing app. Verify that the app functions correctly in the production environment.

Dockerizing the MySQL Database

In this chapter, we will dockerize the MySQL database for our real estate listing app. Dockerizing the database allows us to manage the database as a separate container. Let’s proceed with the following steps:

1. Update the docker-compose.yml File: Open the docker-compose.yml file and update the db service as follows:

db:
  image: mysql:8.0
  environment:
    MYSQL_ROOT_PASSWORD: secret
    MYSQL_DATABASE: laravel
    MYSQL_USER: laravel
    MYSQL_PASSWORD: secret
  volumes:
    - db_data:/var/lib/mysql

2. Build and Run the Updated Docker Containers: In the terminal or command prompt, navigate to the root directory of your Laravel project and run the following command to build and run the updated Docker containers:

docker-compose up -d --build

3. Test the Deployed App: With the updated Docker containers running, visit http://localhost:8000 in your browser to access the deployed real estate listing app. Verify that the app functions correctly with the database containerized.

Related Article: How To Add Elements To An Empty Array In PHP

Performance Considerations

In this chapter, we will discuss some performance considerations for our real estate listing app. Optimizing performance is crucial for delivering a fast and responsive user experience. Let’s proceed with the following considerations:

1. Caching: Implementing caching can significantly improve the performance of your app. Laravel provides built-in support for caching using popular caching drivers like Redis and Memcached. Consider caching frequently accessed data, such as listings or user profiles, to reduce the load on the database and improve response times.

2. Database Indexing: Proper indexing of database tables can improve query performance. Analyze the queries executed by your app and identify the columns that are frequently used in the WHERE or JOIN clauses. Add indexes to these columns to speed up the queries.

3. Eager Loading: When retrieving records that have relationships with other records, use eager loading to reduce the number of database queries. Eager loading allows you to retrieve all the related records in a single query, rather than making separate queries for each relationship.

4. Asset Optimization: Optimize your assets, such as JavaScript and CSS files, to reduce their size and improve loading times. Minify and concatenate your assets, enable compression, and leverage browser caching to ensure efficient delivery to the client’s browser.

5. Use Queues: For time-consuming tasks or tasks that can be performed asynchronously, consider using queues to offload the work from the main application thread. Laravel provides a useful queueing system that integrates with various queue drivers, such as Redis, Beanstalkd, and Amazon SQS.

6. Load Balancing: If your real estate listing app experiences high traffic, consider implementing load balancing to distribute the load across multiple servers. Load balancing helps ensure high availability and improves the overall performance and scalability of your app.

Best Practices for Laravel Development

In this chapter, we will discuss some best practices for developing Laravel applications. Following these practices can help improve the maintainability, scalability, and performance of your real estate listing app. Let’s proceed with the following best practices:

1. Use Laravel’s Directory Structure: Stick to Laravel’s recommended directory structure to keep your code organized and easy to navigate. Place models, controllers, and views in their respective directories, and follow the naming conventions provided by Laravel.

2. Utilize Blade Templates: Take full advantage of Laravel’s Blade templating engine to create reusable and modular views. Use Blade’s control structures, such as loops and conditionals, to dynamically generate content. Avoid mixing PHP code directly in your views and leverage Blade’s features, like layouts and components, to keep your views clean and maintainable.

3. Practice Route Caching: In production environments, it’s recommended to cache your routes using Laravel’s route caching feature. This can significantly improve the performance of your app by reducing the time it takes to resolve routes.

4. Implement Validation: Always validate user input before storing or processing it. Laravel provides a useful validation system that allows you to define validation rules and error messages in a user-friendly way. Use Laravel’s validation rules to sanitize and validate user input, ensuring data integrity and preventing security vulnerabilities.

5. Leverage Laravel Mix: Laravel Mix is a wrapper around Webpack that simplifies asset compilation and bundling. Use Laravel Mix to compile your JavaScript and CSS assets, apply versioning, and leverage other features like autoloading and hot module replacement.

6. Write Unit Tests: Unit testing is crucial for ensuring the correctness and stability of your app. Write unit tests for critical parts of your codebase, such as models, controllers, and services. Laravel provides a testing framework that makes it easy to write and run tests. Aim for comprehensive test coverage to catch and prevent bugs early in the development process.

Code Snippet: Adding Google Maps Integration

In this chapter, we will provide a code snippet that demonstrates how to integrate Google Maps into your real estate listing app. Google Maps integration can enhance the user experience by displaying the location of each listing on a map. Let’s proceed with the following code snippet:

First, make sure you have included the Google Maps JavaScript API in your app. You can do this by adding the following script tag to your main layout file (e.g., resources/views/layouts/app.blade.php):


Next, in the view file where you want to display the map (e.g., resources/views/listings/show.blade.php), add the following HTML code:

<div id="map"></div>

In your JavaScript file (e.g., resources/js/app.js), add the following code to initialize the map and display the location:

function initMap() {
    const mapElement = document.getElementById('map');
    const lat = parseFloat('{{ $listing->latitude }}');
    const lng = parseFloat('{{ $listing->longitude }}');
    const location = { lat, lng };

    const map = new google.maps.Map(mapElement, {
        center: location,
        zoom: 12
    });

    new google.maps.Marker({
        position: location,
        map: map,
        title: '{{ $listing->title }}'
    });
}

// Call the initMap function when the page has finished loading
google.maps.event.addDomListener(window, 'load', initMap);

Replace YOUR_API_KEY with your actual Google Maps API key. Also, make sure you have latitude and longitude attributes in your Listing model, which store the coordinates of the listing’s location.

Finally, compile the assets by running the following command:

npm run dev

With the above code snippet in place, the map will be displayed on the listing details page, showing the location of the listing with a marker.

Related Article: Docker How-To: Workdir, Run Command, Env Variables

Code Snippet: Implementing Social Sharing

In this chapter, we will provide a code snippet that demonstrates how to implement social sharing functionality in your real estate listing app. Social sharing allows users to share listings on social media platforms, increasing visibility and engagement. Let’s proceed with the following code snippet:

First, include the following HTML code in the view file where you want to display the social sharing buttons (e.g., resources/views/listings/show.blade.php):

<div class="social-sharing">
    <a href="https://www.facebook.com/sharer/sharer.php?u={{ urlencode(Request::url()) }}" target="_blank" rel="noopener noreferrer">
        Share on Facebook
    </a>
    <a href="https://twitter.com/intent/tweet?url={{ urlencode(Request::url()) }}" target="_blank" rel="noopener noreferrer">
        Share on Twitter
    </a>
    <a href="https://www.linkedin.com/shareArticle?url={{ urlencode(Request::url()) }}" target="_blank" rel="noopener noreferrer">
        Share on LinkedIn
    </a>
</div>

In your CSS file (e.g., resources/sass/app.scss), add the following styles to customize the appearance of the social sharing buttons:

.social-sharing {
    margin-bottom: 20px;

    a {
        display: inline-block;
        margin-right: 10px;
        color: #fff;
        background-color: #007bff;
        padding: 8px 12px;
        border-radius: 4px;
        text-decoration: none;
    }
}

Finally, compile the assets by running the following command:

npm run dev

With the above code snippet in place, the social sharing buttons will be displayed on the listing details page, allowing users to share the listing’s URL on Facebook, Twitter, and LinkedIn.

Advanced Technique: Building an API for Mobile Apps

In this chapter, we will explore an advanced technique: building an API for mobile apps. Exposing an API allows mobile apps to interact with your real estate listing app and retrieve data. Let’s proceed with the following steps:

1. Create an API Controller: Run the following command to create an API controller:

php artisan make:controller API/ListingController --api --model=Listing

This will generate a new controller file named ListingController.php in the app/Http/Controllers/API directory. The --api option tells Laravel to generate the controller with API-specific methods and middleware.

2. Define API Routes: Open the routes/api.php file and define the routes for the API endpoints. For example:

Route::apiResource('listings', API\ListingController::class);

3. Implement API Methods: Open the ListingController.php file in the app/Http/Controllers/API directory and implement the API methods. These methods should return JSON responses instead of HTML views. For example:

public function index()
{
    $listings = Listing::all();
    return response()->json($listings);
}

public function store(Request $request)
{
    $listing = Listing::create($request->all());
    return response()->json($listing, 201);
}

// Implement other API methods (show, update, destroy) as needed

4. Optional: Add API Authentication: If you want to secure your API endpoints, consider implementing authentication. Laravel provides various authentication mechanisms, such as token-based authentication using Laravel Sanctum or JWT.

5. Test the API: With the API endpoints implemented, you can now test them using a tool like Postman or by making HTTP requests from your mobile app. Verify that the API returns the expected JSON responses and that the mobile app can consume the data.

Advanced Technique: Implementing Real-Time Updates with Pusher

In this chapter, we will explore another advanced technique: implementing real-time updates in our real estate listing app using Pusher. Real-time updates allow users to receive instant notifications when new listings are added or existing listings are updated. Let’s proceed with the following steps:

1. Set Up Pusher: Sign up for a free Pusher account at https://pusher.com and create a new app. Note down the app credentials, including the app ID, key, secret, and cluster.

2. Install the Pusher PHP Library: Run the following command to install the Pusher PHP library:

composer require pusher/pusher-php-server

3. Configure Pusher Credentials: Open the .env file and add the following lines to configure the Pusher credentials:

PUSHER_APP_ID=your_app_id
PUSHER_APP_KEY=your_app_key
PUSHER_APP_SECRET=your_app_secret
PUSHER_APP_CLUSTER=your_app_cluster

Replace your_app_id, your_app_key, your_app_secret, and your_app_cluster with the corresponding values from your Pusher app.

4. Broadcast Events: In the ListingController.php file, add the following code to broadcast events when new listings are created or updated:

use App\Events\ListingCreated;
use App\Events\ListingUpdated;

public function store(Request $request)
{
    $listing = Listing::create($request->all());
    event(new ListingCreated($listing));
    return response()->json($listing, 201);
}

public function update(Request $request, Listing $listing)
{
    $listing->update($request->all());
    event(new ListingUpdated($listing));
    return response()->json($listing);
}

5. Create Event Classes: Run the following commands to create event classes for listing creation and update:

php artisan make:event ListingCreated
php artisan make:event ListingUpdated

This will generate two event classes in the app/Events directory.

6. Implement Event Listeners: Run the following commands to create event listeners for listing creation and update:

php artisan make:listener SendListingCreatedNotification --event=ListingCreated
php artisan make:listener SendListingUpdatedNotification --event=ListingUpdated

This will generate two listener classes in the app/Listeners directory.

7. Implement the Event Listeners: Open the event listener classes and implement the necessary logic to send real-time updates using Pusher. For example:

use App\Events\ListingCreated;
use App\Events\ListingUpdated;
use Illuminate\Support\Facades\Log;
use Pusher\Pusher;

class SendListingCreatedNotification
{
    public function handle(ListingCreated $event)
    {
        $listing = $event->listing;

        $pusher = new Pusher(
            env('PUSHER_APP_KEY'),
            env('PUSHER_APP_SECRET'),
            env('PUSHER_APP_ID'),
            [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                'useTLS' => true
            ]
        );

        $pusher->trigger('listings', 'created', [
            'listing' => $listing
        ]);

        Log::info('Listing created event broadcasted.');
    }
}

// Implement the SendListingUpdatedNotification listener similarly

8. Subscribe to Pusher Channels: In your JavaScript file (e.g., resources/js/app.js), add the following code to subscribe to the Pusher channels and handle the real-time updates:

import Echo from 'laravel-echo';

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    encrypted: true
});

window.Echo.channel('listings')
    .listen('.created', (data) => {
        console.log('New listing created:', data.listing);
        // Handle the new listing creation in your app
    });

// Implement similar code to handle the '.updated' event

9. Compile the Assets: Run the following command to compile the assets with the Pusher integration:

npm run dev

With the above steps completed, your real estate listing app will broadcast real-time events when new listings are created or updated. The connected clients will receive the events and can handle them accordingly, such as updating the listings in real time.

You May Also Like

How to Write to the Console in PHP

"A guide on using PHP to log messages to the console. Learn how to use the echo function and print statement, along with best practices for writing to the console in... read more

Processing MySQL Queries in PHP: A Detailed Guide

Learn how MySQL queries are returned in PHP and the steps involved in this process. Understand the syntax, retrieve and access the result set, display the output, and... read more

Preventing Redundant MySQL Queries in PHP Loops

Minimizing redundant MySQL queries within PHP loops is essential for optimizing code performance. This article explores various techniques, such as query caching,... read more