アプリ関連ニュース

Tips & best practices for Laravel 8

This article will show you the mysterious tricks that might help you when writing code with Laravel.

1.Use local scopes when you need to query things

Laravel has a nice way to write queries for your database driver using Query Builder. Something like this:

$orders = Order::where(‘status’, ‘delivered’)->where(‘paid’, true)->get();

This is pretty nice.But this bit of code can be better written if we use local scopes.

Local scopes allow us to create our Query Builder methods we can chain when we try to retrieve data. For example, instead of ->where() statements, we can use ->delivered() and ->paid() in a cleaner way.

First, in our Order model, we should add some methods:

class Order extends Model
{
...
public function scopeDelivered($query) {
return $query->where('status', 'delivered');
} public function scopePaid($query) {
return $query->where('paid', true);
}
}

When declaring local scopes, you should use the scope[Something] exact naming. In this way, Laravel will know that this is a scope and will make use of it in your Query Builder. Make sure you include the first argument that is automatically injected by Laravel and is the query builder instance.

$orders = Order::delivered()->paid()->get();

For more dynamic retrieval, you can use dynamic local scopes. Each scope allows you to give parameters.

class Order extends Model
{
...
public function scopeStatus($query, string $status) {
return $query->where('status', $status);
}
}$orders = Order::status('delivered')->paid()->get();

Laravel uses by default where[Something] to replace the previous scope. So instead of the previous one, you can do:

Order::whereStatus(‘delivered’)->paid()->get();

Laravel will search for the snake_case version of Something from where[Something]. If you have status in your DB, you will use the previous example. If you have shipping_status, you can use:

Order::whereShippingStatus(‘delivered’)->paid()->get();

2.Magic scopes

When building things, you can use the magic scopes that are already embedded

  • Retrieve the results by created_at , descending:
           User::latest()->get();
  • Retrieve the results by any field, descending:
           User::latest('last_login_at')->get();
  • Retrieve results in random order:
           User::inRandomOrder()->get();
  • Run a query method only if something’s true:

3.Do not store model-related static data in configs

Instead of this:

BettingOdds.php

class BettingOdds extends Model
{
   ...
}

config/bettingOdds.php

return [
   'sports' => [
      'soccer' => 'sport:1',
      'tennis' => 'sport:2',
      'basketball' => 'sport:3',
      ...
   ],
];

And accessing them using:

config(’bettingOdds.sports.soccer’);

I prefer doing this:

BettingOdds.php

class BettingOdds extends Model
{
protected static $sports = [
'soccer' => 'sport:1',
'tennis' => 'sport:2',
'basketball' => 'sport:3',
...
];
}

And access them using:

BettingOdds::$sports['soccer'];

Because it’s easier to be used in further operations:

class BettingOdds extends Model
{
protected static $sports = [
'soccer' => 'sport:1',
'tennis' => 'sport:2',
'basketball' => 'sport:3',
...
];public function scopeSport($query, string $sport)
{
if (! isset(self::$sports[$sport])) {
return $query;
}

return $query->where('sport_id', self::$sports[$sport]);
}
}

Now we can enjoy scopes:

BettingOdds::sport('soccer')->get();

4.Use collections instead of raw-array processing

Back in the days, we were used to working with arrays in a raw way:

$fruits = ['apple', 'pear', 'banana', 'strawberry'];foreach ($fruits as $fruit) {
echo 'I have '. $fruit;
}

Now, we can use advanced methods that will help us process the data within arrays. We can filter, transform, iterate and modify data inside an array:

$fruits = collect($fruits);$fruits = $fruits->reject(function ($fruit) {
return $fruit === 'apple';
})->toArray();['pear', 'banana', 'strawberry']

Tsuki





JavaScriptでQRコードをスキャンする

今回はJavaScriptでQRコードをスキャンするライブラリcozmo/jsQR(https://github.com/cozmo/jsQR)を紹介します。

前回の記事「PHP QRコード生成ライブラリ「endroid/qr-code」」ではQRコードの生成方法を紹介しましたが、今回は生成したQRコードをスマートフォンやPCのWebカメラを使用してJavaScriptでスキャンする方法を紹介いたします。

続きを読む

Windows上でAndroid向けゲームがプレイ可能に

GoogleがPC向けサービス Google Play Games を The Game Awards に合わせて発表しました。
2022年にPC上でAndroid向けゲームがプレイ可能になるとの事です。
公開された動画は The Game Awards のTwitterで見ることができます。

続きを読む

Converting images into a pdf in python

Last weekend, my friend asked me to help him something about rearranging images and converting them into a pdf with only portrait view and sorting by modified date . But the images were not sorted by that and some in landscape. They were in chaos. Actually there are many online tools to do that. But most of them were not compatible with all what I wanted. Then I decided to do with a python program and wrote the following small code block. Let’s take a look.

I’ve used the image library called Pillow(PIL) and built-in module named os.

Overall program flow is as follow.

  1. Request user inputs for a pdf filename with path and image folder path to be converted.
  2. With os module, image files are sorted by modified date.
  3. Looping the sorted files, rotate the images which are in landscape, to be in portrait with the help of Pillow(PIL) and push the images into an empty list named img_list[ ].
  4. Finally convert the images list to a pdf.


from PIL import Image
import os

# Function to sort by modified dates
def getfiles(dirpath):
    a = [s for s in os.listdir(dirpath)
         if os.path.isfile(os.path.join(dirpath, s))]
    a.sort(key=lambda s: os.path.getmtime(os.path.join(dirpath, s)))
    return a

# declare an empty list 
img_list = []

# Request user input for pdf filename and image folder path
pdf_filename = input("Enter the filename of pdfincluding path to be exported : ")
folder = input("Enter the path of images folder : ")

files = getfiles(folder) # get the files sorted by modified dates
print('Processing....')

for count, filename in enumerate(files):
    image = Image.open(folder+'/'+filename) #open each file
    
    # To change as portrait layout for landscape images
    width, height = image.size 
    if(width>height):
        image = image.transpose(Image.ROTATE_90)
    # Append each processed image in img_list[]    
    img_list.append(image)

# All images in img_list[] are converted to a pdf
img_list[0].save(pdf_filename, "PDF" ,resolution=100.0, save_all=True, append_images=img_list[1:])
print("Done!")

This program is very simple but it can be modified to be more useful for other cases. I hope you enjoy that.

By Asahi



Flutter boosts it’s mobile performance

Google Flutter 2.8, the latest version of open source, cross-platform toolkit for building web, mobile, and desktop applications, has been released, with some improvements in mobile performance and better service compatibilities.

Flutter 2.8′ has been released on December 8 including with Flame Modular 2D Game Engine(v1.0), a game engine built on Flutter to be able to create games faster with flutter.

Flutter 2.8 brings performance boost and new Dart features - 9to5Google
Image Credit : Google

Google said mobile apps built with Flutter 2.8 should be faster and use less memory. The company said it is leveraging its experience with great Google apps such as Google Pay to make Flutter more efficient and provide profiling and optimization better.

It also makes it easy to connect to back-end services like Firebase and Google Cloud. In addition to supporting the production quality of Google Ads, including major camera updates and built-in web plugins.

Furthermore Dart 2.15, a programming language update that offers improved concurrency, improved enums, and optimizations that reduce memory usage by 10%. Also offering capabilities including stateful hot reload. Google also is exploring higher-level abstractions to make it easier for developers to get running faster. 

Flutter is for building cross-platform applications from a single code base. The goal is to change the way applications are created so that mobile, web, desktop, and embedded applications can be developed using a single toolset. The framework currently has 375,000 apps on the Google Play Store, as well as iOS apps available on the Apple App Store.

Yuuma



アプリ関連ニュース

お問い合わせはこちら

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

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

お問い合わせフォーム