Dylan  Iqbal

Dylan Iqbal

1560212936

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.

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.

#laravel #php

What is GEEK

Buddha Community

How to use Repository Pattern in Laravel
Seamus  Quitzon

Seamus Quitzon

1595201363

Php how to delete multiple rows through checkbox using ajax in laravel

First thing, we will need a table and i am creating products table for this example. So run the following query to create table.

CREATE TABLE `products` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 `description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Next, we will need to insert some dummy records in this table that will be deleted.

INSERT INTO `products` (`name`, `description`) VALUES

('Test product 1', 'Product description example1'),

('Test product 2', 'Product description example2'),

('Test product 3', 'Product description example3'),

('Test product 4', 'Product description example4'),

('Test product 5', 'Product description example5');

Now we are redy to create a model corresponding to this products table. Here we will create Product model. So let’s create a model file Product.php file under app directory and put the code below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'name','description'
    ];
}

Step 2: Create Route

Now, in this second step we will create some routes to handle the request for this example. So opeen routes/web.php file and copy the routes as given below.

routes/web.php

Route::get('product', 'ProductController@index');
Route::delete('product/{id}', ['as'=>'product.destroy','uses'=>'ProductController@destroy']);
Route::delete('delete-multiple-product', ['as'=>'product.multiple-delete','uses'=>'ProductController@deleteMultiple']);

#laravel #delete multiple rows in laravel using ajax #laravel ajax delete #laravel ajax multiple checkbox delete #laravel delete multiple rows #laravel delete records using ajax #laravel multiple checkbox delete rows #laravel multiple delete

I am Developer

1597487833

Country State City Drop Down List using Ajax in Laravel

Here, i will show you how to create dynamic depedent country state city dropdown list using ajax in laravel.

Country State City Dropdown List using Ajax in php Laravel

Follow Below given steps to create dynamic dependent country state city dropdown list with jQuery ajax in laravel:

  • Step 1: Install Laravel App
  • Step 2: Add Database Details
  • Step 3: Create Country State City Migration and Model File
  • Step 4: Add Routes For Country State City
  • Step 5: Create Controller For Fetch Country State City
  • Step 6: Create Blade File For Show Dependent Country State City in Dropdown
  • Step 7: Run Development Server

https://www.tutsmake.com/ajax-country-state-city-dropdown-in-laravel/

#how to create dynamic dropdown list using laravel dynamic select box in laravel #laravel-country state city package #laravel country state city drop down #dynamic dropdown country city state list in laravel using ajax #country state city dropdown list using ajax in php laravel #country state city dropdown list using ajax in laravel demo

How to Send E-mail Using Queue in Laravel 7/8

Today I will show you How to Send E-mail Using Queue in Laravel 7/8, many time we can see some process take more time to load like payment gateway, email send, etc. Whenever you are sending email for verification then it load time to send mail because it is services. If you don’t want to wait to user for send email or other process on loading server side process then you can use queue.

Read More : How to Send E-mail Using Queue in Laravel 7/8

https://websolutionstuff.com/post/how-to-send-e-mail-using-queue-in-laravel-7-8


Read Also : Send Mail Example In Laravel 8

https://websolutionstuff.com/post/send-mail-example-in-laravel-8

#how to send e-mail using queue in laravel 7/8 #email #laravel #send mail using queue in laravel 7 #laravel 7/8 send mail using queue #laravel 7/8 mail queue example

I am Developer

1597469369

Crop and Resize Image Before Upload In Laravel Using with jQuery Copper JS

Crop and resize image size before upload in laravel using jquery copper js. In this post, i will show you how to crop and resize image size in laravel using jQuery copper js in laravel.

This laravel crop image before upload using cropper js looks like:

laravel crop image before upload

Laravel Crop Image Before Uploading using Cropper js Tutorial

Laravel crop image before upload tutorial, follow the following steps and learn how to use cropper js to crop image before uploading in laravel app:

  • Step 1: Install New Laravel App
  • Step 2: Add Database Details
  • Step 3: Create Migration & Model
  • Step 4: Add Route
  • Step 5: Create Controller By Artisan
  • Step 6: Create Blade View
  • Step 7: Make Upload Directory
  • Step 8: Start Development Server

Read More => https://www.tutsmake.com/laravel-crop-image-before-upload-using-jquery-copper-js/

Live Demo Laravel Crop image Before Upload.

#laravel crop image before upload, #laravel crop and resize image using cropper.js #ajax image upload and crop with jquery and laravel #crop and upload image ajax jquery laravel #crop image while uploading with jquery laravel #image crop and upload using jquery with laravel ajax

How To Create Zip File Using Ziparchive in Laravel

In this tutorial i will show you how to create zip file using zipArchive in laravel. Some times client’s have requirements to have functionalities like create zip file for documentation or images and download it.

So, at that time we can find many laravel packages to perform this task. But here, i am show you to how to create zip file in laravel using zipArchive without any package. Laravel provide ZipArchive class for create zip file in laravel,So i will use ZipArchive in laravel.

How To Create Zip File Using Ziparchive in Laravel

https://websolutionstuff.com/post/how-to-create-zip-file-using-ziparchive-in-laravel

#laravel #ziparchive #how to create zip file using ziparchive in laravel #ziparchive in laravel #make zip in laravel #ziparchive laravel example