Categories
Laravel

Oauth Tutorial – Part 1 – Setting up Facebook

Advertisements

Last week I promised that I will be creating some tutorials regarding Oauth and Laravel’s Socialite plugin. Today, we will start with setting up each website and creating an app on these sites to accept our OAuth requests.

Firstly, we will start with Facebook, then head on over to Twitter and Google+. I am using these as my website won’t be for developers. It will be for everyday people so I don’t expect them to have a Github or Linkedin account. If however, I want to implement these at a later date, I will post the setup of them here for you to see.

Start off by going to developers.facebook.com/apps/ and click on the “+ Add a New App” button. We then get a sort of pop up window which will ask us to select our desired target. We want the website, so click on that to get started.

Within the next page, it will ask us to search for an existing app or create a new one. For the purpose of our tutorial, we will create a new app called “FooBar”. A type that in and select “Create New Facebook App ID”. This is not a test version of another app (we will come to that in a bit) so we want to leave that as it is and select a category for our app. I’ll just select “Entertainment”, but you can select what ever’s right for you at the time. Click on “Create App ID” and it will bring you to a nice setup page.

We can ignore the SDK code part as we won’t be needing that. Tell Facebook about your website. I’m going to stick with foobar and give the URL https://foobar.com and the mobile site will be the same. This is because we won’t have m. when our site is going to be responsive (won’t it?). After you have type in the URL to your website, click on the “Next” button and it will give you a “Next Steps” section, we can ignore this for now and click on “Skip Quick Start”, this will then send us over to our dashboard.

You can browse your dashboard, but for this tutorial, that is pretty much it. Keep in mind that you will need your “App ID” and “App Secret” for use in the future.

Check out my previous tutorial on using OAuth with localhost when needing and SSL Certificate Please also let me know what you think in the comments and if this tutorial has helped you in any way, please also let me know how you think I could improve on it for future posts.

Categories
PHP

Local OAUTH – Curl: (60) SSL certificate : Unable to get local issuer certificate

Advertisements

I’ve seen a couple of questions regarding the error “Curl: (60) SSL certificate : Unable to get local issuer certificate” and thought I would post some steps on the best way of setting it up locally.

I use XAMPP as my local development environment, but this will work with WAMP or LAMP enviroments too.

(I know I should use Vagrant as my local environment, but I haven’t got round to getting it up and running just yet).

Firstly, we need to download an SSL certificate to use for our local set up, to do this, head over to Github and save the file. The best place to save it is in C:/xampp/apache/conf/ssl.crt. There is already a crt file here, but I have test that one and it doesn’t work. You can either overwrite that one, or keep the name “ca-bundle.crt”, I generally keep to the same name that way the other file is there in case you need it in the future.

Now you need to open up your php.ini file find the line “curl.cainfo” (if it isn’t there) add/change it to… curl.cainfo = “C:xamppapacheconfssl.crtca-bundle.crt”. Restart your Apache server and test it out using any Oauth API you are using or going to use for your projects.

This is the best and most permenant way to handle SSL within your local environment and I highly recommend it.

If you feel there is a better way or you need help, then please feel free to comment below.

Categories
General

Quick Update

Advertisements

Lots have been going on recently, so I do apologise for not writing a post as of late. I was made redundant by my previous employee due to lack of funds and not being able to push enough work my way. Luckily, the guys there are pretty cool and was happy to be my reference for any future employment. I was really lucky to find a new workplace. As soon as I left, I started my new position with Pulse8 Broadband.

Now I am working on a single website, and trying to push it up to be an amazing website to visit. I am looking migrate the website over to Laravel in the near future. This will make development easier and faster to push out updates.

I’m looking forward to the future and any Laravel tutorials I post from now on will be with version 5 as I’ve already pushed myself over and have loved it since it’s official release.

Hope to speak to my followers again soon and as always, if you have any questions, please feel free to ask.

Categories
Laravel PHP

Unique slug for news articles using Laravel’s unique valitation

Advertisements

Just recently at work, I had to change the way my news articles worked. We have a client who has Holiday Homes, and they have news articles per park. When I redeveloped the website in Laravel, I created a one to many relationship based on… “One park has many news articles”.

I really should have created a many to many relationship. There could be the same articles per park, but I was young and naive. Because I worked in this way, I needed to figure out a way where I could have the same or similar articles with the same article slug, but unique only to that park.

So say if I had a park in Cornwall, I could create an article which has the slug of “owners-update”. This slug could be used on another park which is in Devon, but the slug couldn’t then be used again in Cornwall as it has been done.

Add a similar rule to the one below in your create method. You will get the results which I was looking for…

slug' => 'required|unique:news,slug,NULL,id,park_id,' . $input['park_id'],

This rule will then ONLY apply to an article with the same park id.

Ref: Laravel Unique Rule

Categories
General

Website Update

Advertisements

As you can see, it has been a while since my last post. However, I have been busy trying to push updates over to my website. This is to help strengthen the relationships between you and I.

You can now share any articles you like by scrolling to the bottom of each, and clicking on the “Share This” button. Each social website which you can share with will pop up. However, I do need to improve on this. It will automate text titles, images (when I start adding them) and using selected paragraphs.

I would like to encourage all of my readers to share any posts which you find useful so that it can help other as well. I have also added a Recommended Reading page which you can use to find new and interesting books which have caught my eye. In the future, as I being to read each of those books (which I will), I will post reviews on what I believe has and hasn’t helped me and hopefully help you decide on what books will be helpful for you.

If there is anything you would like me to investigate further and create posts on certain situations with a resolution, then please write a comment below detailing what you need help with and I will do my best to investigate and create solutions to these problems.

Categories
Laravel

UTF-8 causing problems for Social and Email Websites Laravel

Advertisements

I’ve been developing a couple of projects which use UTF-8 encoding on my databases, but have found that this has been problematic recently. Mobile phones and tablets now use emoticons which can cause problems for us, UTF-8 users.

So how do we fix this issue?

Well, let me explain below…

Recently, I was testing out one of my creations and sent a message using an emoticon. Laravel started spitting out errors and it confused me as to why this was happening. After a quick search, I found that in order to save these emoticons to the database, I need to change my encoding from UTF-8 to UTF8MB4.

I found a little snippet which allowed me to change my tables encoding

ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;

Fantastic I thought, I did this with every table which needed it and then tested my app again, I got the same error?!? 😮

One thing I missed out, was that I need to set Laravel’s settings to the same encoding as my database. Move on over to app/config/database.php and you will find the ‘connections’ array. I’m using mysql, and I found just what I was looking for…

'charset' => 'utf8', 'collation' => 'utf8',

Change this to…

'charset' => 'utf8mb4', 'collation' => 'utf8mb4_general_ci'

And you are done. Let me know if you still have any problems and your stories with how you managed to fix this issue. 🙂

Categories
Laravel

Laravel 4: How To Use Jquery UI Sortable

Advertisements

Laravel 4: How To Use Jquery UI Sortable

Click and drag sorting

I needed a way to change the sort order of my data inside of an admin interface which I have created. After a little looking around, I found many tutorials which would show how to get this done with JQuery. But wouldn’t show the best way to handle this data (and in my case using Laravel to handle this data). I dug around for quite a bit, but I ended up finding this lovely little tutorial by dragonfire1119 which was called How To Use Jquery UI Sortable In Laravel 4.

The only trouble is, when you follow this tutorial, it could be tidied up a little, here is my version…

// Place this inside your View

@foreach($categories as $category)
    sort me
@endforeach

Here is the JQuery…

$(document).ready(function () {
    $('.sortable').sortable({ cursor: 'move', axis: 'y', update: function () {
        var order = $(this).sortable('toArray');
        $.post('{{ URL::route('Sliders::sort') }}', { order: order })
    }
    });
});

And then your Controller will look like this…

<?php
public function sort() {
    $input = Input::get('order');
    $i = 1;
    
    foreach($input as $value) {
        $banner = Banner::find($value);
    
        $banner->sort_by = $i;
        $banner->save();
        
        $i++;
    }
}

The JQuery and Controller could also look like this…

$(document).ready(function () {
    $('.sortable').sortable({ cursor: 'move', action (event, ui) {
        var data = $(this).sortable('serialize');
        
        $.ajax({ data: data, type: 'POST', url: '{{ URL::route('Sliders::sort') }}' });
    }
    });
});

Updated Controller…

<?php
public function sort() {
    $input = Input::get('item');
    $i = 0;
    foreach($input as $value) { $banner = Banner::find($value);
        $banner->sort_by = $i;
        $banner->save();
        $i++;
    }
}

I think that both work just as well and it is down to personal preference. If you would like to know where I got the second method from, you can take a look here.

As always, if you have any comments/suggestion the please feel free to let me know in the comments.

Categories
Laravel

Laravel AJAX Tutorial Using HTML5’s FormData

Advertisements

Laravel AJAX Tutorial Using HTML5’s FormData

For this tutorial, I will show you guys how I managed to create an image uploader for your profile image. This is very similar to how Facebook’s/Twitter’s functionality.

Routes

First of all, let’s create the routes, for this, we will need to create a get and post route…

<?php
Route::get('{username}', 'UsernameController@show');
Route::post('{username}/upload', 'UploadController@profileImage');

Controllers

Remember that you can name the controllers and methods anything you like, as long as you keep everything consistent. Now we need to create the controllers and methods which are as follows…

<?php
// User Controller, index mehod
public function show($username) {
    $user = User::where('username', $username)->first(); $userData = User::find($user->id)->UserDetail;

    return View::make('user', array( 'userData'=> $userData ))->with('user', $user);
}

We are trying to get the user’s information where it matches in the URI. As you can see, I have a one to one relationship with a user and a user’s information (called UserDetail). I believe the user array could be placed along with the user data array. However, I decided to place this inside the with a method.

Now we need to handle the image data which will upload the image to the background. Without anyone knowing it’s happening…

<?php
// UploadController, profileImage method
public function profileImage($username){
    $user = User::where('username', $username)->first();

    $temp = $_FILES['upload']['tmp_name']; $image = $_FILES['upload']['name'];
    $ext = pathinfo($image, PATHINFO_EXTENSION);
    
    $newFilename = uniqid($user->id);
    
    if(!is_dir("images/$username/")) { mkdir("images/$username", 0777); }
    
    $img = Image::make($temp);
    
    $img->fit(130, 130);
    
    $src = "images/$username/$newFilename.$ext";
    
    $img->save($src);
    
    $query = User::find($user->id)->profileImage; $query->src = $src;
    $query->alt = $username . '\'s Profile Image';
    $query->save();
}

Firstly, we need to match the username with the username in the URI, after this, we grab the image and process it. Please note that I am using the Intervention/Image package, which you can easily grab and install to implement it on your website. We check to see if the directory exists, if it doesn’t, then we create it with r/w permissions. I then use the image package to create an image which is 130px X 130px, the fit method will automatically crop the image so it doesn’t look stretched and horrible. We then give it a source which tells it where to save this image which then gets saved. Afterwards, we call the database and find the user to set the image src and alt rows.

Blade templates

Now that we have all the backend magic happening, we actually need to create a view which displays the form and automatically refreshes the image upon upload completion…

@extends('layout')

@section('content')

    <div class="row">
    
        <div id="profile-wrapper">
        
            <div class="large-2 columns pull-left">
                <img class="profile-thumb th" src="/{{ $user->profileImage->src }}"
                    alt="Profile Image" />
            </div>
            
            <h2>About</h2>
            
            @if(isset($loggedIn) && $loggedIn->username == $user->username)
                <a href="#" class="upload-link"> Upload a file </a>
                <div class="hidden-upload">
                    {{ Form::open(array(
                        'action' => array('User::upload',
                        $user->username),
                        'files' => 'true',
                        'id' => 'image-form')) }}
                        {{ Form::file('upload', array('class' => 'profile-upload')) }}
                    {{ Form::close() }}
                </div>
            @endif
        </div>
    
        {{ $userData->about }}
    </div>

@stop

Javascript (Ajax)

We only want to show this hidden form if the user is logged in and it’s the same logged in user which is seeing their own profile. As you can see, we are using Laravel’s blade syntax which makes this page look a lot cleaner and easier to see what is going on. Right, now we need the JQuery which will send the image to the post controller we recently created…

<script>
    if(isset(user)) {
        form.change(function() {
            var formData = new FormData($('form')[0]);
            
            jQuery.ajax({
                url: '{{ $user->username }}/upload'
                data: formData,
                processData: false,
                contentType: false,
                type: 'post',
                success: function(
                    window.location.reload(true);
                )
            })
        })
    }
</script>

I have created my own scripts.blade.php which gets placed into my layout.blade.PHP, you can do the same, or you can include this within the page itself. I then added an if statement to avoid any errors for when a user isn’t logged in. For our JQuery creates a new format function and passes in the form we created, we then call the ajax method and pass it some parameters.

  • URL: sets the URL to where the image needs to get passed to, this is the route we created above.
  • data: sets the data to formData.
  • processData and contentType are both set to false, this has to be set to avoid any future errors.
  • type: We set this to post as it is a post method.
  • success: On success, it will refresh the window to display the newly uploaded image.

Styles

There you guys have it, this is all we need to create our really awesome AJAX upload form. However, you guys might be wondering, how do we hide the form? We here are the optional steps so you can create a hidden form which gets shown upon mouse hover…

.upload-link {
    position: absolute;
    top: 100px;
    left: 35px;
    z-index: 0;
}

#profile-wrapper:hover .upload-link {
    display: inline; background: rgba(0, 0, 0, 0.8);
    color: #fff;
    padding: 2px;
}

.hidden-upload {
    position: absolute;
    top: 100px;
    left: 35px;
    z-index: 1;
}

.hidden-upload .profile-upload {
    opacity: 0;
}

Now, that is all there is (I promise). If you have any questions, comments or feedback, then please feel free to drop a comment down below. I always like to read what you guys have to say and love replying back to you. I hope you look forward to my next Blog post.

Categories
Laravel

Laravel user Registration and Login

Advertisements

Using Laravel packages to help us

This will be a fairly simple tutorial as I’m not re-creating the wheel here. I started by developing a login/registration system by myself until I start talking to people in Laravel’s IRC. There is a package which did everything I needed it to do which was as follows…

  • Register a user with the following credentials; Username, Email, Password and of course Confirm Password.
  • The user then gets sent an email to confirm registration.
  • The user confirms registration and can now use the website by logging in.
  • The link in case the user forgets the password, which then creates a link to confirm so the user can then change his/her password.
  • Remember me functionality.
  • Logging out
  • Completely customisable in terms of layout and functionality.

Some people had spoken about a Laravel package which does all of this called Zicaco/confide. This package is absolutely brilliant and does everything I could ask for whilst still maintaining the simplicity of migrating it into something you have already developed.

We need to start off by installing this package, place “zizaco/confide”: “~4.0@dev” into your Composer’s require key. You then place ZizacoConfideServiceProvider’, inside Laravel’s provider’s array. Finally, add this into Laravel’s aliases array ‘Confide’ => ‘ZizacoConfideFacade’, .

(PLEASE NOTE: I am currently using version 3.2.* of this package and I currently haven’t upgraded. I am sure that the experience will be similar, but if you have any queries then feel free to email me).

Once you have installed your package successfully, you can run these commands to get everything up and running… php artisan confide:controllerphp artisan confide:routescomposer dump-autoload. And as the docs say, you are good to go.

You can test it out by going to localhost/users/create to see what it has made for you. Of course, you can go on and change the layout, the control and anything else which you find you need to change.

If you need any help, then please let me know and I will try to help you out. I will also be trying to upgrade to the latest version and will release a step by step guide on how to do this.

Categories
General Laravel

Thoughts on my social networking site and what has changed

Advertisements

Carrying on with my social networking website

I’ve had a lot to think about when it comes to the where I want to take my website. Firstly, do I really want to take on such a big task of trying to beat Facebook on my own, when they have a huge team? The answer to that is no, no I don’t. I have always had some great ideas with what I wanted to do. However, the fact is, I couldn’t carry this out on my own.

What could I do instead? I figured I should go for something which possibly hasn’t been done before. It could be similar to something which has already been done, that way I can keep my ideas on the straight and narrow. There have been so many instances where I would come up with these ideas and they would just explode, I would get so excited about these new prospects. However, because most of my thoughts have rarely been carried out before, I would get frustrated because I couldn’t find the help I needed.

Expanding the social idea

What if I created a website which could help like-minded people? With projects too big for them to carry out themselves? It then came to me, like a brick smacking into my face. I would create a website where users could explain a project they want to create, and then find people close by with similar ideas. They could then meet up somewhere and express these ideas, then they could create the project into something real.

My website will be about users coming in to make a project. You then find people who are interested and meet up with them to make this project a reality. As it’s initially a project, my website won’t be asking you about wages or some sort of payment, it will be up to you to make that part a reality.

I would like to apologise for the lack of posts lately. Things have been a bit hectic for me and my family. Please bear with me. I can assure you, I will still be posting. I will be making my website a reality for people to enjoy.