How to use Repository Pattern in Laravel

How to use Repository Pattern in Laravel

The Repository Pattern in Laravel is a very useful pattern with a couple of great uses. The first use is the abstraction that it provides. Meaning, it adds another layer between your application logic and your database.

The Repository Pattern in Laravel is a very useful pattern with a couple of great uses. The first use is the abstraction that it provides. Meaning, it adds another layer between your application logic and your database.

When tackling the separation of concerns, this is very important. Another benefit is how easy it makes it swap out your backend technology.

For instance, let’s say you are using MySQL and want to change to MongoDB. Since the Repository Pattern uses interfaces as contracts, your application logic will remain the same and all you have to do is change out the repository. Sounds easy, right?

Let’s dive in with a simple example.

Creating the Repository Interface

We need an interface to act as a contract for our repositories. What do I mean by contract?

Just like a written contract which describes the confines of a specific obligation, an interface is the same for our code.

It says that any class implementing the interface must perform specific actions. Or, in our case, must contain specific methods… Right.

I will use the blog scenario and create a post repository, as well as a comment repository. So, create a folder inside of the app folder and name it Repositories.

Then, create a file and name it PostRepositoryInterface.php. This will be our interface. Within that interface, you will want to add this code:

namespace App\Repositories;

interface PostRepositoryInterface
{

}

Now, we will need the contracts, or methods, that we want our toPostRepository implement. It will look something like this:

namespace App\Repositories;

interface PostRepositoryInterface
{
    /**
     * Get's a post by it's ID
     *
     * @param int
     */
    public function get($post_id);

    /**
     * Get's all posts.
     *
     * @return mixed
     */
    public function all();

    /**
     * Deletes a post.
     *
     * @param int
     */
    public function delete($post_id);

    /**
     * Updates a post.
     *
     * @param int
     * @param array
     */
    public function update($post_id, array $post_data);
}

Notice how there are no opening and closing curly braces. That is because no logic is stored in the interface – only the methods or declaration that we want our class to implement.

Creating the Repository

Now, we need to create our class. Within the same folder, Repositoriescreate a file and name it PostRepository.php. For this class, we will use the implements keyword to specify that we want to implement our interface. It should look like this:

namespace App\Repositories;

class PostRepository implements PostRepositoryInterface
{

}

We must create the methods that declared in our interface. If we don’t, we will get an error at runtime and we will not be able to use our class. Go ahead and add the logic that we will use to work without posts. For this, I will include our Eloquent model Post.

namespace App\Repositories;

use App\Post;

class PostRepository implements PostRepositoryInterface
{
    /**
     * Get's a post by it's ID
     *
     * @param int
     * @return collection
     */
    public function get($post_id)
    {
        return Post::find($post_id);
    }

    /**
     * Get's all posts.
     *
     * @return mixed
     */
    public function all()
    {
        return Post::all();
    }

    /**
     * Deletes a post.
     *
     * @param int
     */
    public function delete($post_id)
    {
        Post::destroy($post_id)
    }

    /**
     * Updates a post.
     *
     * @param int
     * @param array
     */
    public function update($post_id, array $post_data)
    {
        Post::find($post_id)->update($post_data);
    }
}

Our class is now happy because it is using all of the methods defined by our interface. Now that we have our class and our interface created, we need to register our repository with Laravel’s container.

Registering our Repository with Laravel’s IoC Container

Create a file called BackendServiceProvider.php within the same folder – Repositories. This file will serve as a connector to Laravel’s IoC Container and allow us to use dependency injection to inject our repository interfaces. More on that in a second …

Here is the BackendServiceProvider.php:

namespace App\Repositories;

use Illuminate\Support\ServiceProvider;

class BackendServiceProvider extends ServiceProvider
{

    public function register()
    {
        $this->app->bind(
            'App\Repositories\PostRepositoryInterface',
            'App\Repositories\PostRepository'
        );
    }
}

The one thing to notice here is the order in which the interface and the class are bound. If you try and bind App\Repositories\PostRepository before App\Repositories\PostRepositoryInterface, you will get an error. You must bind the interface first.

Still with me?

Just to make sure you’re following along, you should have a folder structure like this:

- app
--- Repositories
------ BackendServiceProvider.php
------ PostRepositoryInterface.php
------ PostRepository.php

Of course, there will be other folders and files within the app directory, I hope you get the point.

Using the Repository in a Controller

It’s time to use our shiny, new repository. The place to use this is our controller. I will assume that you have a PostController.php class and that is your controller that handles everything to do with your posts. If you use some other controller, that is fine too.

What we want to do is inject our interface into the controller through its constructor when the controller gets instantiated. That way we can use the repository for all of our interactions with our posts model. Check it out:

namespace App\Http\Controllers;

use App\Http\Requests;
use App\Repositories\PostRepositoryInterface;

class PostController extends Controller
{

    protected $post;

    /**
     * PostController constructor.
     *
     * @param PostRepositoryInterface $post
     */
    public function __construct(PostRepositoryInterface $post)
    {
        $this->post = $post;
    }

    /**
     * List all posts.
     *
     * @return mixed
     */
    public function index()
    {
        $data = [
            'posts' => $this->post->all()
        ];

        return view('templates.posts', $data)
    }

}

The first thing that we did is inject oursPostRepositoryInterface into our constructor.

Then, we set our instance$post variable to an instance of our objectPostRepository through our interface. This allows us to call the methods in our classPostRepository like we did in the methodindex(). Now we can do something like this:

$this->post->update($data_array);
$this->post->delete($post_id);
$this->post->get($post_id);

This keeps us from directly accessing our model like Post::find$id); which adds another layer of abstraction to our application. Don’t forget, should we stop using MySQL and start using MongoDB, or some other backend technology, all we have to do is swap out our logicPostRepository. This works because we are accessing the repository through our interface.

This means that the code in our controller would not change at all. That’s a big win!

More than one Repository? Sure

So, you need to create another repository because just having one repository is lame. Right? All you need to do is create an interface and then create a repository. Then, register them with Laravel’s IoC Container in our backend service provider file. I’ll use a Comment model to show you how.

Our directory would now look like this:

In app folder

- Repositories
--- BackendServiceProvider.php
------ PostRepositoryInterface.php
------ PostRepository.php
------ CommentRepositoryInterface.php
------ CommentRepository.php

You would create the comment repository interface the same exact way as we did the post repository interface:

CommentRepositoryInterface.php
namespace App\Repositories;

interface CommentRepositoryInterface
{
    // Define all methods here but remember not to use curly braces.
    public function all(); // Like this..
}

And our CommentRepository.php
namespace App\Repositories;

use App\Comment;

class CommentRepository implements CommentRepositoryInterface
{
    // Must use all methods that were defined in the CommentRepositoryInterface here
    public function all()
    {
        return Comment::all();
    }
}

The last thing that you will need to do is register it with the IoC Container in our BackendServiceProvider.php. That file will now look like this…

namespace App\Repositories;

use Illuminate\Support\ServiceProvider;

class BackendServiceProvider extends ServiceProvider
{

    public function register()
    {
        $this->app->bind(
            'App\Repositories\PostRepositoryInterface',
            'App\Repositories\PostRepository'
        );

        $this->app->bind(
            'App\Repositories\CommentRepositoryInterface',
            'App\Repositories\CommentRepository'
        );
    }
}

Again, pay attention to the order in which you list your interface and class.

Finished. Doesn’t that feel good? You should have a fully functional repository design pattern implemented with Laravel 5.

If you have any questions or comments, please post them below.

Clear Cache in Laravel 6.8 App using Artisan Command Interface (CLI)

Clear Cache in Laravel 6.8 App using Artisan Command Interface (CLI)

In Laravel 6 tutorial, we learn how to use PHP artisan command interface (CLI) to clear the cache from Laravel 6.8 application. How To Clear Cache in Laravel 6.8 Application using Artisan Command Line Interface (CLI)? How to clear route cache using php artisan command? How to easily clear cache in Laravel application? How to clear config cache in PHP Laravel via artisan command? How to clear Laravel view cache? How to Reoptimized class in Laravel via artisan CLI?

Today in this tutorial, we are going to learn how to clear route cache, laravel application cache, config cache, view cache and reoptimized class in a Laravel 6.8 application using artisan command-line interface.

I’m pretty sure many of you may have found yourself gotten into the situation where you do not see changes in the view after making the changes in the app.

Laravel application serves the cached data so caching problem occurs due to the robust cache mechanism of Laravel.

But, if you are still facing this issue, then you do not have to worry further. Let me do the honour of introducing you some of the best artisan commands to remove the cache from your Laravel app via PHP artisan command line interface.

Artisan is the command-line interface included with Laravel. It provides a number of helpful commands that can assist you while you build your application.

Table of Contents

  • Clear Route Cache in Laravel
  • Clear Laravel Application Cache
  • Clear Config Cache via PHP Artisan
  • Clear Laravel View Cache
  • Reoptimized Class
Clear Route Cache in Laravel

Laravel caching system also takes routes in consideration, to remove route cache in Laravel use the given below command:

php artisan route:cache
Clear Application Cache in Laravel

Run the following command to clear application cache:

php artisan cache:clear
Clear Config Cache in Laravel

Run the following command to clear config cache:

php artisan config:cache
Clear View Cache in Laravel

Run the following command to clean your view cache:

php artisan view:clear
Reoptimize Class

Run the below command to reoptimize the class loader:

php artisan optimize

Conclusion

We have completed this Laravel 6 tutorial, In this tutorial we learned how to use php artisan command to clear the cache from your Laravel application. We have answered the following questions in this article.

  • How to clear route cache using php artisan command?
  • How to easily clear cache in Laravel application?
  • How to clear config cache in PHP Laravel via artisan command?
  • How to clear Laravel view cache?
  • How to Reoptimized class in Laravel via artisan CLI?

Now, it’s your time to let me know what do you think about this laravel 6 article. Go forth and try these super awesome artisan commands and let me know how these commands are helping you.

Get Weather Data with Laravel Weather

Get Weather Data with Laravel Weather

Get Weather Data with Laravel Weather. Laravel Weather is a good package which we can use to get weather data. It's a wrapper around Open Weather Map API (Current weather). A wrapper around Open Weather Map API (Current weather)

🌤️ A wrapper around Open Weather Map API (Current weather)

Installation

You can install the package via composer:

source-shell
composer require gnahotelsolutions/laravel-weather
Usage
text-html-php
$weather = new Weather();

// Checking weather by city name
$currentWeatherInGirona = $weather->get('girona,es');

// You can use the city id, this will get you unambiguous results
$currentWeatherInGirona = $weather->find('3121456');

Units

By default the package uses metric for Celsius temperature results, this can be modified using the configuration file or on the fly:

text-html-php
$weather = new Weather();

$currentWeatherInGirona = $weather->inUnits('imperial')->get('girona,es');

Language

By default the package uses es for the description translation, this can be modified using the configuration file or on the fly:

text-html-php
$weather = new Weather();

$currentWeatherInGirona = $weather->inLanguage('en')->get('girona');

Guzzle Client Instance

If you need to use another instance of Guzzle, to modify headers for example:

text-html-php
$weather = new Weather();

$guzzle = $this->getSpecialGuzzleClient();

$currentWeatherInGirona = $weather->using($guzzle)->get('girona');

Testing

source-shell
composer test

Laravel Sweet Alert | How to use the SweetAlert package in Laravel PHP

Laravel Sweet Alert | How to use the SweetAlert package in Laravel PHP

Sweet Alert is a laravel wrapper around #sweetalert javascript library for showing alert or notification message. This is a great package created by rashid, and this laravel package is very famous because it has tonnes of features you can choose from.

Sweet Alert is a laravel wrapper around #sweetalert javascript library for showing alert or notification message.

This is a great package created by rashid, and this laravel package is very famous because it has tonnes of features you can choose from.