Monday 4 December 2017

For reasons I can't start to explain, I'll be moving this blog over to medium.com.
I'll try to move the existing contents as well, but surely future posts will be on medium.
Find me on medium @sdkcodes
Bye!

Get in line, I'm moving over to MEDIUM

Saturday 2 December 2017

If you're like me (and every other developer), you must have now realized the importance of using queues. Queues give you the power of async programming by allowing you run some important (any) task in the background.

Let's think about it this way: in a typical web app, we have the usual request-response cycle where your user sends a request to your server, your server processes the request, when it's done, it sends back a response to the user (browser) - this is the way it works. 

Now, there is no problem with this, except in a situation whereby during the request, your server needs to send mails (to one or more users), generate pdf files, make calls to 4 other external APIs and so on, that's getting too long right?

In a typical request-response, your user has to wait until your server is done with all those tasks before they get a feedback. These tasks can take anywhere between 30 seconds to forever, which is a lot, if you ask me.

Instead, how about, we do it such that user sends request, and get feedback immediately? cool right? But I hear you ask, what happens to our tasks? Well, we are not discarding them, we are just pushing them to background workers, so our users do not have to wait.

Setting up queue workers with laravel is quite easy, on your local server and when deployed to a cloud hosting environment, but not quite so when deploying to a shared hosting environment. However, there's a simple solution for this as well.

For this post, I'm assuming you already have your queue configured (the drivers and all).

We will be combining the power of Laravel Task SchedulingLaravel Queues and Cron Jobs


Steps:

  • Set up a cron job on your server like such: * * * * * php /path-to-project/artisan schedule:run >> /dev/null 2>&1
    The above is telling your cron to run once every minute. So, once every minutes, it runs your scheduled laravel task.
  • Now, in your code, in the Kernel.php file: App\Console\Kernel, add the following line:  $schedule->command('queue:work --tries=3')
    ->cron('* * * * * *')
    ->withoutOverlapping();

    So that your Kernel.php now looks like this: 
  • You should be all set up now. Dispatch new jobs to your queue, and see them all executed every minute.
Quite easy, eh!
That'd be all from me, for now. Bye!

Using laravel Queues on shared hosting: A simple guide

Thursday 16 November 2017

You're done crafting your artisan-esque laravel app on your local environment (be it homestead, laragon, xampp, valet or whatever) and now you need to show your app to the world.
There are cloud hosting solutions like Heroku, DigitalOcean etc that makes it easy to deploy laravel apps, however, we might not always have those options available to us which brings our old friend - cpanel shared hosting - into the picture.

Regardless of what you might have read out there, you can fully deploy Laravel to a shared hosting environment, and have it run fine.
For the purpose of this blogpost, I'm going to assume your host allows you SSH access, and you can use git (you really should be).
Steps:

  1. Push your project to your remote git repo
  2. Using a tool such as putty or bitvise, SSH into your server. Now, a terminal should open for you to use.
    You can run few terminal commands to be sure you're good to go. e.g
    ls to list directories.
    You should be able to see the files and folders on your server including www (alias public_html).
  3. Now, get the url for your remote repo, like: https://github.com/sdkcodes/samplelaravelrepo.git
  4. Then in your server terminal, clone the repository: git clone https://github.com/sdkcodes/samplelaravelrepo.git
  5. Because your .env file won't be committed, you need to create one on your server, run touch .env to create your env file and copy the contents from your local env to the remote one. Updating values where necessary.
    PS: remember to set environment value to production and update the app url.
  6. Run composer install or composer update for composer to install your dependencies.
  7. Now, your laravel app should be on the server. To be sure, you can run an artisan command such as php artisan inspire
  8. Copy (not cut) all the contents of your laravel's public folder (i.e css/, js/ index.php etc) to the public_html folder of your server.
  9. If you try to access your url now, you should get an error. That's because the path to your bootstrap.php and autoload.php files are not properly set.
  10. To fix that, open the public_html/index.php file, then change lines
    require __DIR__.'/../bootstrap/autoload.php';
    To
    require __DIR__.'/../projectfoldername/bootstrap/autoload.php';

    AND 
    $app = require_once __DIR__.'/../bootstrap/app.php';
    To
    $app = require_once __DIR__.'/../projectfoldername/bootstrap/app.php';
  11. Access your app's url now, it should be accessible.
  12. From your server's terminal, you can run all artisan's commands and even git commands.
Anytime you make changes to the project locally, all you just need to do is push to git, then do git pull in your server's terminal (and run composer update) if necessary.
Note that, if you make any changes to the public folder locally, then you'd have to manually update the public_html content.


I hope this helps you.

How to Deploy Laravel to a Shared Hosting Server

Friday 14 July 2017

Sometimes, when you are creating a web app, you might want to create some routes for your API. 
Laravel fortunately, laravel makes this easy by shipping with a routes/web.php and routes.api.php file. 
The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group, which provides features like session state and CSRF protection. The routes in routes/api.php are stateless and are assigned the api middleware group.
The api middleware helps you to guard your api routes and you can easily guard multiple routes by defining as follows:

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Or

Route::middleware('auth:api')->group(function(){
Route::get('users', "UserController@index");
        Route::post('users', "UserContoller@save");
        Route::get('home', function(){
               return 'something';
        });
});

After creating and setting up your routes and it's guard, now you'll need to authenticate users making calls to your API. You might possibly want to use Laravel Passport or other sophisticated means of authentication, but the purpose of this tutorial is to show you a simple method and still relatively secure.

Step 1:

Add an api_token column to your users table
$table->string('api_token')

You can fill this column manually or create a random string for every new user signing up
Tip: str_random(60)

Step 2:

On every call to your api routes, add the query parameter ?api_token=[your_api_token] and laravel will automatically compare the token to the one in the database

It's that simple.

Simple Api Authentication For Laravel

Wednesday 1 February 2017

Programming is a very funny craft - errors pop up every where every time when they feel like.

So, I was working on one of my usual long term apps, I then tried logging in to the admin area of the web app, and I got a blank page in return. I checked the source of the page, and only about 3-4 lines of javascript was displayed. The error must have been just before immediately after this line (I whispered to myself).

(I think I should mention at this point that, the app is made using PHP [codeigniter], Javascript [JQuery] and the usual HTML, CSS, Bootstrap)

I delved into the code to unravel our bug, but then, there was no clue as to what could be wrong. "This code was still working last night, and I'm pretty sure no body else had access to the code", I mumbled to myself.

Okay, I had an idea, let me turn on error reporting (humm, on a production app), I did turn on error reporting and got a little clue.

Undefined property on object title... blah blah blah, in file .....php 
That appeared on about 20 lines, (Okay, this would imply the property is being accessed in a loop, I said). I went into the said file, nothing seemed wrong. This is getting more serious than I thought.



I went to check CodeIgniter error logs, and then I found this

PHP Fatal error:  Allowed memory size of 268435456 bytes exhausted (tried to allocate 9865442 bytes) in dashboard_view.php on line 78

I still appear to be clueless, you can't blame me, can you? I have never come across this type of error.
Then I went to the "developer's bible" (StackOverflow) , this was where I saw that the most likely culprit is that a code is trying to retrieve a large data from the database at a go.
Delving back into the code again, I found out there was indeed a particular statement retrieving all records from a database without limits.
Yes, this code worked fine when I had just about 2,000 rows in the table, but now, I have about 50,000 rows and fetching them all into memory all at once is nothing wise.

Now, lesson learnt.

An Unexpected Memory Bug I encountered

Tuesday 18 October 2016

Really don't have much to say,
https://github.com/sdkcodes/codeigniter_bootstrap_alert
Head over to the link, it says it all.
Thanks

I just published a tiny helper library

Wednesday 12 October 2016

So, you've just started your programming journey and it has been a pretty mixed feeling - sometimes feeling extremely excited when your code runs, and the other times , extremely frustrated when you have no idea what's wrong . Well, either ways, I'm happy to welcome you to the brotherhood.
In this post, I'll be talking about a concept in programming (and consequently in JavaScript) which is very important and this is the concept of variables.
Variables are very important and essential in programming and all programming languages, and I should I have talked about it alongside another related important concept (Data Types), but I'll do that in a separate post.
What are Variables?
A variable is a name in memory that stores a value.
Let me take you back to your basic mathematics algebra class:
Let x = (22/5 + 2)
Assuming (22/5 + 2) is a long expression, we have just saved this expression in a variable x, such that, anytime we use x in our subsequent calculations, we are actually referring to (22/5 + 2). You dig?
Now, coming back to JavaScript, this is how variables are used:
i = 1000;
In the case above, i is the variable name and 1000 is the value stored in the variable.
From the above example, whenever we use the name i in other parts of the same program, the value 1000 will be substituted.
I want to think it's making sense now.
In JavaScript, it is advisable to declare a variable first before using it, and you do this by using the var keyword. As in:
      var name;
      name = "Elusoji Sodeeq"
In the first line of code above, what we did is called "variable declaration". We are telling the JavaScript interpreter, :"hey, I want to register this variable name with you".
On line 2, what we did is called "variable assignment". We assigned value "Elusoji Sodeeq" to the variable we declared earlier. This is like saying, : "hey, JavaScript interpreter, remember the variable I registered with you earlier. Good. I want to give it a value now".
Now, that's it, we have just created and used a variable in JavaScript.
Variables can be used to store values of any type. I'll talk about Data Types in another post.
You can read further here
That will be all from me, for now.

Javascript variables :- a quick introduction

Sunday 10 July 2016

Woh!! So, like I said on my twitter timeline earlier, I'll be posting a number of tutorial, tips for aspiring, beginning and maybe even intermediate programmers on this blog. And for starters, I'll make this first post a super simple one.
I'll show you how to get the value typed in an html textbox using javascript.
Now, if you are very good with javascript or you're are already an experienced programmer, you can look the other way as this tutorial is not meant for you.

I'm going to use the sample html code below:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
 <title>Trying Javascript</title>
</head>
<body>
 <form>
  <input type="text" name="username" id="username" placeholder="Input your Username">
  <br>
  <input type="text" name="email" id="email" placeholder="email@example.com">
  <button type="button" onclick="showDetails()">Show Details</button>
 </form>
</body>
<script>
 function showDetails(){
  var username = document.getElementById('username');
  var email = document.getElementById('email');
  alert('Your username is: ' + username.value + '\n\
   And Your email is: ' + email.value);
 }
</script>
</html>
I'll go through what's happening in the code above now
From line 1-13, I did the normal html stuff, but two things you need to pay attention to here are the id attributes of input element and the onclick attribute of the button element.
Assigning an id to any html element makes it possible for our javascript code to find that element and use it comfortably.
The onclick attibute makes sure that out the button responds when it is clicked on. When the button is clicked, the showDetails() function will be executed.

From line 15 - 20, we defined our showDetails() function, and inside the function, we firstly retrieve the two input elements using their respective IDs. (remember the id we set earlier in out html).
Now, we can do anything with the values of those elements, in this example, i chose to pop up an alert when the button is clicked. The values can be used for just about anything you want, e.g for validation, for sending to a server script using ajax, or just saving in cookie.

Now, that's all from me for now. If anything seem unclear, do not hesitate to let me know
Take care!!

How to get Form Input value using Javascript

Thursday 28 May 2015

Hello everyone like you all can see, this is a new born baby  blog. On here, I will be talking about pretty much anything. That is, from myself, to tech, to writing, to my life and a whole lot of other interesting things you might enjoy.

This is going to be a good ride, I hope...

Welcome to my home