Twitter

Laravel Migration Error: Specified Key Was Too Long; Max Key Length is 767 Bytes

by Adam Patel

So you’ve got your database connected up to your app and now you try to run your initial database migration – but it doesn’t work. You get an error:

Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

Laravel is starting to seem like hard work now, right? For every step, there’s another headache.

The solution is to add two lines of code to the public boot function, located in AppServiceProvider.php (App/Providers/AppServiceProvider.php)

At the top of the file, under namespace, add

use Illuminate\Support\Facades\Schema;

Without this line, the second line will not work and it will produce an error when you try to run the migration. The second line is the line starting ‘Schema’, which should be added to the boot function. I’ve printed the whole boot function below for context (because there’s no point knowing what code to add if you don’t know where to add it).

public function boot()
    {
        Schema::defaultStringLength(191);
    }

The migration should now run properly. And thankfully, laravel starts to behave a bit more smoothly from this point onwards.

How To Connect A Laravel App To A MySQL Database

by Adam Patel

MacBook Pro with images of computer language codes

If you’ve been following my series of articles on setting up a laravel app on shared hosting, at this point, you’ve installed Laravel Breeze for user registration and authentication. Of course, without connection to a MySQL database, this isn’t going to work. So that’s our focus for this post.

This step is relatively straightforward if you know how.

Step #1 – Create A MySQL database via your cPanel

Click on MySQL databases and create a new database. It’s that simple. You don’t have to make any tables or anything – laravel will do that for you. The database just needs to exist so that the app an connect to it.

Step #2 – Setup The Database Connection

In the root folder of your Laravel app, there is a hidden file that is probably currently called .env.example. This is the only file you need edit in order to connect to the database. This file creates constants which will then be used in config/database.php. But you don’t need to touch that file in order to get this working.

Within your .env.example file, you’ll need to edit lines 10 to 15 as follows:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=sharedhostinguser_databasename
DB_USERNAME=sharedhostinguser_MySQLusername
DB_PASSWORD='password between single quotes'

The first three lines remain the same.

DB_DATABASE is the database name. When you create databases on sharedhosting, they take the form of your cpanel username followed by an underscore, followed by whatever name you give the database.

The username follows the same pattern. If this is the first time ever that you’re setting up a MySQL database, you may also need to create a user and then attribute the user to the database.

Your password goes between single quotes.

That’s it. Save the changes.

Step #3 – Rename .env.example as .env

Finally, you need to rename the file so that the app can recognise it and use the settings you’ve just set.

Step # 4 – Test the connection by performing a database migration

The easiest way to know whether your database is connected is to perform a database migration.

php artisan migrate

If you don’t get some green lines of text telling you that various tables have been created, you might get an error telling you that a key was too long. If so, don’t worry, I’ve got you covered in this post. If it worked successfully, move right on to this article.

How To Install Laravel Breeze on a Shared Hosting Account

by Adam Patel

black laptop computer turned on displaying blue screen

If you’re building a web app, the chances are you want user registration and authentication so that users of your app can have their own user accounts. Laravel 8 makes this easy – sort of – by giving you starter kits. It took me quite a while to figure out how exactly to use these, but here’s what you do to make breeze work on shared hosting.

Open the terminal in cPanel and navigate to the root directory of your laravel app. Once you’re there, it only takes two commands to install it.

The first line is this…

composer require laravel/breeze --dev

Then, you want this command…

php artisan breeze:install

This takes a bit of time, but when it’s finished, you’ll eventually get instructions to run an npm command in order to complete the process. You’ll then probably realise (I did) that npm is not available on shared hosting accounts.

However, I found that all the necessary files are created ANYWAY – without running any further commands.

If you now navigate in your browser to yourdomain.com/login, there will indeed be a page there.

How To Stop Redirect To Public Folder On Fresh Laravel 8 App

by Adam Patel

So, you’ve installed a fresh laravel 8 app on your shared web hosting account using Softaculous and now you’ve got this problem that when you go to your domain, it redirects to /public/ after 5 seconds.

Correcting this is a three step process.

Step 1 – Rename server.php as index.php in your root folder

That’s pretty self explanatory. Just select the server.php file and rename it as index.php, overwriting the current index.php file.

Step 2 – Move the contents of the public folder to the root folder

Again, self explanatory.

Step 3 – Open up your .htaccess file in the root folder and replace the content with the following…

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>
Options -MultiViews -Indexes
 
RewriteEngine On
 
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
 
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
 
# Handle Front Controller...
RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
 
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(css|js|images|trainer-cv)/(.*)$ public/$1/$2 [L,NC]

And that’s it! You’ll find the redirect has stopped and the splash screen now shows at yourdomain.com.

Why Laravel Is My Framework Of Choice

by Adam Patel

When I first learned professional web app development, I learned on Ruby on Rails. And I liked it quite a lot. Ruby is syntactically a really nice language and will always be my ‘mother tongue’ of programming, if there is such a thing. There’s only one thing I really don’t like about Rails. It’s expensive to host. Whether you use Heroku or AWS or something else, Rails requires some setup on the server which means that experimenting with it is kind of expensive. Why build a web app on the free version of Heroku, if you’re looking at £500+ a year to host it normally?

When I first graduated from Makers Academy, this was a rude awakening for me. But having played the field a little (lol!) and worked with a number of different frameworks, Laravel is becoming my favourite. It’s very similar in structure to Rails, but it runs on PHP rather than Ruby. And PHP just works on any standard Apache server setup. Not expensive at all! I can host a bunch of Laravel apps for about £100 a year. This makes experimentation relatively free!

Laravel wasn’t the easiest framework to learn. I’m personally not a huge fan of the documentation. Thank goodness for YouTube!

How To Create A Hyperlink in HTML

by Adam Patel

A hyperlink is a piece of code that allows a user to navigate from the page they are on which contains the link, to another page, simply by clicking the link. You’ve used them thousands of times. This is how they work.

A hyperlink is an a tag, wrapper around the text that will be the link, knows as anchor text.

<a href="#">anchor text</a>

Replace the # with the URL of the page you want to visit.

Replace anchor text with whatever you want the link to say.

The above code. would display on a web page like this:

anchor text

That’s how you code a hyperlink.

How To Host A Subdomain On A Different Server To Your Main Website

by Adam Patel

Now that I develop a lot of projects in Ruby on Rails, they require specialist hosting. The standard shared hosting accounts that host so many websites including those powered by WordPress just don’t provide enough server resources to run a modern and complex web application.

But what if I want to also run a WordPress powered blog as a section of the same domain? This sounds complicated.

It is actually possible to run different subdomains (something.example.com) on different servers.

How?

Create a new A record in the DNS for the domain in question. You can usually do this through your registrar.

You’ll need 2 things in order to do this:

  1. The name of the subdomain you want to create
  2. The IP address of the server you want to point it at.

Creating an A record is then fairly straight forward.

Where it says HOST, type the name of the subdomain. So for example if you’re trying to create blog.example.com, the host would just be “blog”.

Where it says points to, or IP, type the IP address of the server where you’re going to host the subdomain.

Now, you can head over to your hosting account and Add Domain or Addon Domain as is standard practise in CPanel.

For domain to add, type the full name: blog.example.com.

If your domain registrar is GoDaddy, everything should work within about 30 seconds. But for other registrars it can take up to 24 hours.

How To Create A Color-Changing Link in CSS (For Navigation Menus or Anything Else)

by Adam Patel

It’s common in UX design to have web page elements react in some way to user interaction. For example, have a link change colour when the user mouses over it.

This can be achieved using Javascript in the DOM, but equally, it can be done with CSS.

So assume this is the following link code. An a tag inside a nav div.

<div id="nav">
<a href="">link</a>
</div><!-- // nav -->

To style this normally, the CSS would be as follows:

#nav a {color: black;}

And to style the link, when a user hovers over it, we would do:

#nav a:hover {color: blue}

How To Create A Javascript Slide-Out Menu

by Adam Patel

If you’re viewing this website on your mobile device, you may have already used the slide-out menu to navigate around the site. If you haven’t, you can click the yellow square on the top right of the screen to have a look at it without leaving this page.

A slide-out menu is a space-efficient way of creating a navigation menu on a smaller screen device where screen space is at a premium.

In this post I’m going to explain how to implement this type of menu on your website or web-app.

How It Actually Works

In essence, this menu is a div that is not displayed by default, and is given a width value only when the javascript function to do so is called on it.

So, the “slide-out” is actually an illusion. When the page is loaded, by default, the menu div has a width of 0px, and so does not display on the page.

Then, we call a Javascript function on it which gives it a width value of whatever we want, say 250px.

How To Implement It On Your Website

There are three parts to this implementation.

First, there’s the HTML:

<div id="mySidenav" class="sidenav">

<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>

<a href="https://www.adampatel.co.uk/" rel="nofollow">Home</a>
<a href="https://www.adampatel.co.uk/about/">About</a>
<a href="https://www.adampatel.co.uk/portfolio/">Portfolio</a>
<a href="https://www.adampatel.co.uk/cv/">CV</a>
<a href="https://www.adampatel.co.uk/blog/tutorials/">Coding Tutorials</a>
<a href="https://www.adampatel.co.uk/blog/">Blog</a>
</div><!-- // sidenav -->

We have a div called mySidenav which contains a few standard hyperlinks, followed by the closing of the div.

Lines 2 and 3 are also an a tag but they trigger the javascript function that closes the menu.

Second, there’s the CSS…

The CSS we put in the stylesheet will be the values of various CSS properties by default, ie. when the page first loads.

/* The side navigation menu */
.sidenav {
  height: 100%; /* 100% Full-height */
  width: 0; /* 0 width - change this with JavaScript */
  position: fixed; /* Stay in place */
  z-index: 1; /* Stay on top */
  top: 0; /* Stay at the top */
  left: 0;
  background-color: #111; /* Black*/
  overflow-x: hidden; /* Disable horizontal scroll */
  padding-top: 60px; /* Place content 60px from the top */
  transition: 0.5s; /* 0.5 second transition effect to slide in the sidenav */
}

/* The navigation menu links */
.sidenav a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
  transition: 0.3s;
}

/* When you mouse over the navigation links, change their color */
.sidenav a:hover {
  color: #f1f1f1;
}

/* Position and style the close button (top right corner) */
.sidenav .closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}

You’ll notice on line 4, the default width of the div is 0%, so it doesn’t display by default.

Finally, part 3 is the Javascript

Place this code in the head of your HTML.

<script>
/* Set the width of the side navigation to 250px */
function openNav() {
  document.getElementById("mySidenav").style.width = "250px";
}

/* Set the width of the side navigation to 0 */
function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
}
</script>

There are two Javascript functions in this code.

openNav() which selects the mySidenav div and applies a width of 250px to it, thus making the menu slide out when this function is called.

closeNav() does the opposite. It reapplies a width of 0 when the function is called.

But how do we call the function? Well you’ve already seen in the HTML in part 1 that we called one of those functions within the menu. Calling the other is much the same, except we call it from an element that is visible on the page by default, in the case of my website, the menu button.

<div id="call_menu"><span align="center" onclick="openNav()">MENU</span></div>

It’s the onclick=”openNav()” bit that calls the Javascript function and activates the slide-out menu.

And that’s it!

You can of course apply your own colour schemes and fonts by making changes to the CSS.

Test Ruby Project

by Adam Patel

this is a test ruby project to see if and how it appears in the portfolio category.

Copyright 2021. All Rights Reserved. Adam Patel