#Coding

How To Optimize Laravel Code Eloquently With UpdateOrCreate()

by

In beginning of my Laravel learning, I did write more lines of code to perform my task than I write now. I started learning to adopt more eloquent ways of coding for Laravel encourages us to write. One simple task I performed by writing this many number of lines:


$place = PlaceModel::where('id', "132")->first();
if(isset($place))
{
  $place->update(['name' => 'Place Name', 'address' => 'Place Address',]);
}
else
{
  $place = PlaceModel::create([
    'name' => 'Place Name',
    'address' => 'Place Address',
  ]);
}

This many lines of code can be optimised to single statement of line in Laravel Eloquent way. This is ome of the ways to optimize eloquent query on Laravel:

CONTINUE READING

प्रोग्रामिंग: एक परिचय (An Introduction to Programming in Nepali)

by

यस ट्यूटोरियलको लक्ष्य छ तपाईंलाई सकेसम्म चाँडो त्यो चरणमा पुग्ने प्रयास गर्न जहाँ तपाईं उपयोगी प्रोग्रामहरू लेख्न सक्नुहुनेछ। नयाँ प्रोग्रामिंग भाषा सिक्ने एक मात्र तरिका यसमा प्रोग्रामहरू लेख्नु हो। तपाईले प्रोग्राम पाठ कहिँ लेख्न, यसलाई सफलतापूर्वक कम्पाइल गर्न, लोड गर्न, चलाउन, र आउटपुट फेला पार्न सक्षम हुनुपर्दछ।

मैले सरल कारणले गर्दा यो ट्यूटोरियल श्रृंखला को लागी जाभास्क्रिप्ट(javascript) भाषा छानिएको छु। जाभास्क्रिप्ट कोड सिक्न र गर्न सजिलो छ। यसले तपाईंको सिक्ने समयको बचत गर्न सक्दछ। जाभास्क्रिप्ट हरेक आधुनिक वेब ब्राउजरमा स्थापित हुन्छ, त्यसैले तपाईं अहिले जाभास्क्रिप्टमा प्रोग्रामिंग सुरु गर्न सक्नुहुनेछ उही ब्राउजरमा जुन तपाईं यो लेख पढ्न प्रयोग गर्दै हुनुहुन्छ। यदि तपाईं गुगल क्रोम प्रयोग गर्दै हुनुहुन्छ भने, केवल “view” मेनूमा जानुहोस्, “developer” उप-मेनूमा क्लिक गर्नुहोस्, र तपाईंले “javascript console” खोल्ने विकल्प देख्नुहुनेछ।

हामी यी आधारभूत कुरामा ध्यान दिनेछौं: भ्यारीएबल र constants, अंकगणित(arithmetic), control-flow र फंक्शन।

CONTINUE READING

How to Detect Backspace Event in UITextfield and UITextview?

by

In past I have used shouldChangeCharactersInRange delegate method to intercept the change in characters and make a near guess if it was delete-backspace that was tapped by the user. Guess was based on the nature of replacement character provided in method. If replacement character resembled the special escape character "\b" indicating backspace or empty character when view is already empty.

I felt above direction was a bit hacky. I found that based on response logic I was trying to write was giving me side effect of cursor always jumping to the end of text. For example when I tapped in between the characters of text to set the cursor in position and when I pressed backspace in keypad - I detected the event and did my processing to do some changes to text of UITextField and returned false.

What is the clean solution then?

CONTINUE READING

How to add a completion handler block for when I pop UIViewController?

by

Today I pondered about a problem which I had overlooked in past. How to add a completion handler block for when I pop UIViewController?


navigationController?.popViewController(animated: true)

In modal transition, dismissViewControllerAnimated, apple offers an option to call a completion block when dismissal of modal is finished. This is quite handy for various situations where you need to perform certain task like signalling a delegate about something when controller is removed from top of navigation or window.


dismiss(animated: true) {
}

Something similar isn’t offered directly in api for pop and push transitions. We do have been provided with viewDidAppear like methods that may be used to get things certain way. Flexibility and easiness that comes from completion handler of transition is unbeaten.

What we don’t have available from api can be solved by using core animation’s transactions. We group multiple animation related changes together and ensure all changes are run at the same time.

This is fine but how to notify when animation changes are finished?

CONTINUE READING

How to add a custom section header to a table view in Swift

by

Two of a simplest approaches is to use delegate method viewForHeaderInSection and return header view in a form of UIView itself or Custom class inheriting UITableViewHeaderFooterView.

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?

Asks the delegate for a view to display in the header of the specified section of the table view.

Using custom header view in the form of just UIView is good when we have something more than text to show in header.


override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView()
    headerView.backgroundColor = UIColor.systemBlue
    return headerView
}

The other way - more flexible - is to have custom class of UITableViewHeaderFooterView. This approach gives much flexibility to have custom states and properties to handle for complex headers. Example code:

CONTINUE READING

UIToolbar for keyboard inputAccessoryView gives Layout Constraint Errors

by

UIToolbar is very useful control for our input fields for example when we need some action buttons above keypad for input whose keypad type is UIKeyboardType.phonePad. UIKeyboardType.phonePad doesn’t come up with any return key button to dismiss as of now. A simple UIToolbar is very sufficient to provide a button for user to dismiss or do something else.

UIToolbar

A control that displays one or more buttons along the bottom edge of your interface.

The simple code to add UItoolbar to textfield:


let flexibleButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
let done = UIBarButtonItem(title: "Dismiss", style: .done, target: self, action: #selector(doneKeypadTapped))
let bar = UIToolbar()
bar.items = [flexibleButton, done]
bar.sizeToFit()
phonePadTextfield.inputAccessoryView = bar

Now above code does give layout-constraints error indicating that few constraints are not satisfying each other and breaking the layout. It will not break the app in the sense but it does give sense of unease to a developer.

Small snippet from the contraint-error:


<NSLayoutConstraint:0x6000023bec60 ‘TB_Trailing_Trailing’ H:[_UIModernBarButton:0x7fb8bb990f20’Dismiss’]-(20)-|   (active, names: ‘|’:_UIButtonBarButton:0x7fb8bb98e100 )>

CONTINUE READING

How to find out distance between gps location coordinates in Swift?

by

A very simple way to calculate the distance between two given CLLocationCoordinate2D is to first convert them to MKMapPoint which represents two-dimensional point on map.


let point1 = MKMapPoint(clcoordinate1)
let point2 = MKMapPoint(clcoordinate2)

Now, we just use distance(to:) method to receive the distance in meters. Below is the code:

CONTINUE READING

sizeForItemAt of UICollectionView not working in Swift

by

There was a requirement where I was setting custom size for UICollectionViewCell. Custom size wasn’t dynamic but a static tall portrait ratio size. The effective way to set your own custom size is to call implement delegate method of protocol UICollectionViewDelegateFlowLayout:


func collectionView_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return estimatedCollectionSize
}

The problem:

UICollectionView was ignoring size instruction. It was sizing the cells to fit its content only.

CONTINUE READING

Password Laravel Personal/Password Access Client Not Found

by

We must have stumbled on Laravel’s passport sometime for creating authentication api’s for our mobile apps providing full OAuth2 server implementation.

This post uses Laravel 7.x. Our passport installation is


composer require laravel/passport “~9.0”

We will perform the migration where Passport migrations will create the tables our application needs to store clients and access tokens. It will also create Users table for us.


php artisan migrate

We also updated the driver to use passport in config/auth.php


‘api’ => [
            ‘driver’ => ‘passport’,
            ‘provider’ => ‘users’,
            ‘hash’ => false,
        ],

Now in our registration api example when we try to generate access token


$user->createToken(‘MyApp Password Grant Client’)->accessToken;

It gives error:


Auth driver [passport] for guard [api] is not defined.
Personal access client not found.

CONTINUE READING

Get Push Notification While App in Foreground iOS in Swift

by

If the application is running in the foreground, iOS won’t show a notification banner or alert. That is by design.

If we receive local or remote notifications while we app is running in the foreground, we’re responsible for passing the information to our users in an app-specific way. Where to handle and process such request?

userNotificationCenter(_:willPresent:withCompletionHandler:)

Asks the delegate how to handle a notification that arrived while the app was running in the foreground.

If your app is in the foreground when a notification arrives, the shared user notification center calls this method to deliver the notification directly to your app. If you implement this method, you can take whatever actions are necessary to process the notification and update your app. When you finish, call the completionHandler block and specify how you want the system to alert the user, if at all.

CONTINUE READING

Recommended posts