Web Service

Cleaning Up Laravel Controllers

Introduction

Controllers play a huge role in any MVC (model view controller) based project. They’re effectively the “glue” that takes a user’s request, performs some type of logic, and then returns a response.

The Problem with Bloated Controllers

Bloated controllers can cause several problems for developers. They can:

1. Make it hard to track down a particular piece of code or functionality. 

2. Make it difficult to spot the exact location of a bug. 

3. Make it harder to write tests for more complex requests.

The Bloated Controller

For this blog, I am going to use an example UserController:

class UserController extends Controller
{
    public function store(Request $request): RedirectResponse
    {
        $this->authorize('create', User::class);        $request->validate([
            'name'     => 'string|required|max:50',
            'email'    => 'email|required|unique:users',
            'password' => 'string|required|confirmed',
        ]);        $user = User::create([
            'name'     => $request->name,
            'email'    => $request->email,
            'password' => $request->password,
        ]);        $user->generateAvatar();
        $this->dispatch(RegisterUserToNewsletter::class);        return redirect(route('users.index'));
    }    public function unsubscribe(User $user): RedirectResponse
    {
        $user->unsubscribeFromNewsletter();        return redirect(route('users.index'));
    }
}

1. Lift Validation and Authorization into Form Requests



One of the first things that we can do with the controller is to lift any validation and authorization out of the controller and into a form request class.

We’ll use the following Artisan command to create a new form request:

php artisan make:request StoreUserRequest

The above command will have created a new app/Http/Requests/StoreUserRequest.php class that looks like this:

class StoreUserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }
}


We can use the authorize() method to determine if the user should be allowed to carry out the request. The method should return true if they can and false if they cannot. We can also use the rules() method to specify any validation rules that should be run on the request body. 

class StoreUserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize(): bool
    {
        return Gate::allows('create', User::class);
    }
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules(): array
    {
        return [
            'name'     => 'string|required|max:50',
            'email'    => 'email|required|unique:users',
            'password' => 'string|required|confirmed',
        ];
    }
}

Our controller should now also look like this:

class UserController extends Controller
{
    public function store(StoreUserRequest $request): RedirectResponse
    {
        $user = User::create([
            'name'     => $request->name,
            'email'    => $request->email,
            'password' => $request->password,
        ]);
        $user->generateAvatar();
        $this->dispatch(RegisterUserToNewsletter::class);
        return redirect(route('users.index'));
    }
    public function unsubscribe(User $user): RedirectResponse
    {
        $user->unsubscribeFromNewsletter();
        return redirect(route('users.index'));
    }
}

2. Move Common Logic into Actions or Services

Another step that we could take to clean up the store() method could be to move out our "business logic" into a separate action or service class.

class StoreUserAction
{
    public function execute(Request $request): void
    {
        $user = User::create([
            'name'     => $request->name,
            'email'    => $request->email,
            'password' => $request->password,
        ]);
        $user->generateAvatar();
        $this->dispatch(RegisterUserToNewsletter::class);
    }
}

Now we can update our controller to use the action:

class UserController extends Controller
{
    public function store(StoreUserRequest $request, StoreUserAction $storeUserAction): RedirectResponse
    {
        $storeUserAction->execute($request);
        return redirect(route('users.index'));
    }
    public function unsubscribe(User $user): RedirectResponse
    {
        $user->unsubscribeFromNewsletter();
        return redirect(route('users.index'));
    }
}

3. Use Resource or Single-use Controllers

A great way of keeping controllers clean is to ensure that they are either “ resource controllers” or “ single-use controllers”. 

A resource controller is a controller that provides functionality based around a particular resource. So, in our case, our resource is the User model and we want to be able to perform all CRUD (create, update, update, delete) operations on this model. A resource controller typically contains index(), create(), store(), show(), edit(), update() and destroy() methods.

A single-use controller is a controller that only has one public __invoke() method. These are really useful if you have a controller that doesn't really fit into one of the RESTful methods that we have in our resource controllers.

So let’s create a new controller using the following Artisan command:


php artisan make:controller UnsubscribeUserController -i

Notice how we passed -i to the command so that the new controller will be an invokable, single-use controller. We should now have a controller that looks like this:

class UnsubscribeUserController extends Controller
{
    public function __invoke(Request $request)
    {
        //
    }
}

We can now move our method’s code over and delete the unsubscribe method from our old controller:

class UnsubscribeUserController extends Controller
{
    public function __invoke(Request $request): RedirectResponse
    {
        $user->unsubscribeFromNewsletter();
        return redirect(route('users.index'));
    }
}


Conclusion

Hopefully this article has given you an insight into the different types of things you can do to clean up your controllers in your Laravel projects.


Tsuki


Interesting APIs for your dummy data

Sometimes, we need dummy data to add in our projects before the production or you just want to create a fun project with some fun data. Today I will share some interesting data resources , also APIs you can try.

Movies API

The API service is intended for anyone interested in using images and data from movies, TV shows, and actors in their applications. Our API is a system provided by you and your team to acquire and use data and images programmatically.

API : API Overview — The Movie Database (TMDB) (themoviedb.org)

Meals API

The meal API allows you to access random food data and use it in your application. This API includes all meal categories including images, materials, videos, country of each meal and many other features.

API : TheMealDB.com

Jokes API

The random jokes API allows you to fetch random jokes data in an easy way using Fetch, Ajax XHR and etc.

API : icanhazdadjoke

Unsplash API

Unsplash is a website that hosts “beautiful and free images and photos that you can download and use for any project.” You can use that API to fetch photos from Unsplash. You can use the Unsplash API to create an application with a background that changes to a random image at different times of the day.

API : Unsplash Image API | Free HD Photo API

Marvel API

The Marvel Comics API gives developers access to information about Marvel’s vast comic library from anywhere.

API : Marvel Developer Portal

I am sure there are other interesting APIs around the world but that is all from me now. Enjoy the data.

Yuuma



Deploying a machine learning model into a web application with Django

Today, I would like to share about deploying a machine learning model into a web application using Django.

Note : In this article, I will focus only how to deploy a trained machine learning model in a web application with django rather than about the steps of machine learning processes.

First, I will create a simple ML model using multinomial Naive Bayes Classifier with the spam text dataset (spam.csv). The following code is to create spam text detection model.

First, import the necessary libraries.

import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB


And load dataset file with pandas.

data = pd.read_csv("D:\Python\datasets\spam.csv", encoding= 'latin-1')
data.head()
Then extract features and labels using CountVectorizer.
data = data[["class", "message"]]
x = np.array(data["message"])
y = np.array(data["class"])
cv = CountVectorizer()
X = cv.fit_transform(x) # Fit the Data


let’s split this dataset into training and test sets and train the model to detect spam messages

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
clf = MultinomialNB()
clf.fit(X_train,y_train)


And save the model.

import pickle
pickle.dump(clf,open("spamdetection_model.sav", "wb"))

This will output spamdetection_model.sav file. This file will be used in the web app later.


So, Let’s start to develop a Django web app.

mkdir Spamdetection – First make a directory named /Spamdetection for the Django project.

cd Spamdetection – Change directory into the folder created

And to create a Django project, it is needed to run the following command.

D:/Spamdetection>django-admin startproject spamdetectapp

This command create a new directory named spamdetectapp.

To run the djangoapp, the following command is typed in the spamdetectapp directory created.

python manage.py runserver

Copy and open the link http://127.0.0.1:8000/ in a web browser. You should see Django Home page.

Then create views.py inside the same folder to work for getting inputs from users. In the main project folder, create a new folder named ‘templates’ to work with html files and new folders named ‘datasets’ and ‘mlmodels’. Then move spam.csv dataset file into the datasets folder and spamdetection_model.sav file into the mlmodels folder.

Now our project folder will be like that.

Now open settings.py and add ‘templates’ to register in ‘DIRS’ list in the ‘TEMPLATES’ list.


Now inside the urls.py file, add the following codes to configure the urls.

from django.contrib import admin
from django.urls import path

from spamdetectapp import views # add this new line to import views files

urlpatterns = [
    path('admin/', admin.site.urls),
    
    # add these new two lines to configure for home page and result page
    path('', views.home, name='home'), 
    path('result/', views.result, name='result'),
]


And define two functions for home and result in views.py. And create a libs.py in mlmodels folder. In libs.py, we will define a getResult() function to get results from model prediction and use it in views.py.

views.py

from django.shortcuts import render
from mlmodels.libs import getResult

# for default home page view
def home(request):    
    return render(request, 'index.html')

# for result page view
def result(request):	
    message = request.POST['message']
    result = getResult(message)
    return render(request, 'result.html', {'result':result , 'message':message})


libs.py

import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split

def getResult(message):
    import pickle
    data = pd.read_csv("D:\Spamdetection\spamdetectapp\datasets\spam.csv", encoding= 'latin-1')
    data.head()

    data = data[["class", "message"]]
    x = np.array(data["message"])
    y = np.array(data["class"])
    cv = CountVectorizer()
    X = cv.fit_transform(x) # Fit the Data

    model= pickle.load(open("D:\Spamdetection\spamdetectapp\mlmodels\spamdetection_model.sav", "rb"))

    data = cv.transform([message]).toarray()    
    prediction = model.predict(data)
    if prediction == 'ham':
        return 'OK'
    elif prediction == 'spam':
        return 'SPAM'


Now we have done for backend. So, for frontend pages, let’s create index.html and result.html in templates folder.

Index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Spam Text Detection</title>
</head>
<body>
    <h1>Spam Text detection</h1>
    <form action="{% url 'result' %}" method="post">
        {% csrf_token %}
        <p>Message:</p>
        <input type="text" name="message">
        <br>
        <br>
        <input type="submit" value='Predict’>
    </form>
</body>

</html>


result.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Spam Text Detection</title>
</head>
<body>
    <h1>Prediction</h1>
    The Message[{{message}}] is <b>{{result}}</b></body>
</html>


Now all is done. Once the above steps are completed, to stop and restart the server press Ctrl+C and run this command:

D:/Spamdetection/spamdetectapp> python manage.py runserver

And reopen the link in the browser. You will see the index home page.

Let’s test with some messages.

When message is ‘Hello, How are you?’, the result is as follow.

When the message is ‘You got $1000 prize at our shop.’, the result is as follow.

Hope you all enjoyed about this article.

By Asahi



APIs vs. Webhooks

An API (Application Programming Interface) enables two-way communication between software applications driven by requests. A webhook is a lightweight API that powers one-way data sharing triggered by events. Together, they enable applications to share data and functionality, and turn the web into something greater than the sum of its parts.

What is an API?

An API is like a portal through which information and functionality can be shared between two software services. The word “interface” is key to understanding an API’s purpose. Just like a web browser is an interface for a human end user to receive, send, and update information on a web server, an API is an interface that provides software programs with the same functionality. 

What is a webhook?

A webhook can be thought of as a type of API that is driven by events rather than requests. Instead of one application making a request to another to receive a response, a webhook is a service that allows one program to send data to another as soon as a particular event takes place. Webhooks are sometimes referred to as “reverse APIs,” because communication is initiated by the application sending the data rather than the one receiving it. With web services becoming increasingly interconnected, webhooks are seeing more action as a lightweight solution for enabling real-time notifications and data updates without the need to develop a full-scale API.

Next week, I will continue to share the usage of webhook in Laravel.

By tsuki



Clear Cache – Useful Chrome Extension

When we develope websites or mobile apps, one of the important facts we need to think is performance. For example, if the website is using too many images, we need to use cloud storage like S3. Sometimes we need to use cache for better performance.

But when we need to update our code and test again, we have to clear the browser cache to see the changes. Browser cache is cleared by the browser setting. I think it is a little busy for developers. So today I want to share useful chrome extension to clear browser cache.

Clear Cache is a useful chrome extension. Install the extension and select the small recycle icon in your browser to clear the browser cache. There are no confirmations and no extra dialogs to contend with. For easy usage, you can pin in your Chrome browser.

by tsuki




アプリ関連ニュース

お問い合わせはこちら

お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

tel. 06-6454-8833(平日 10:00~17:00)

お問い合わせフォーム