Pt 5: Build a Conversations System with Laravel and Lucid Architecture

in #utopian-io7 years ago (edited)

Conviex Users List

We did some really interesting stuff last time and we'll keep the fun train running today. In this post, we will be up to some more creativity.

Tutorial Contents.

We'll keep it simple. Today, we will:

  • Setup user authentication.
  • Generate and popular our conversations system with test users.
  • Setup our first ModelFactory instance.
  • Build out an interface to view all users in our conversations system.

Difficulty

This tutorial is rated: Intermediate.

Requirements

  • PHP version 5.6.4 or greater
  • Composer version 1.4.1 or greater
  • Lucid Laravel version 5.3.*
  • Our previous code. Github repo

Straight to it.

Hi there. Welcome back. In our last post in this series, we worked on some new features. We granted our users ability to message others with the CreateMessageFeature. We also added Jobs, Repositories, Contracts, Validators and ServiceProviders.

Today, we will be setting up user authentication, creating our views structure and adding some helpers to give our conversations system a little more polish. Let's move on.

Setting up authentication.

We need to setup a basic authentication system. Luckily for us, we don't have to build out the whole thing—we can simply tell Laravel to do it for us. Let's get started. Spin up a terminal inside our conviex directory and run:

C:\xampp\htdocs\conviex>php artisan make:auth

If that ran successfully, you should get this message.

Authentication scaffolding generated successfully.

Next let's spin up our test development server with php artisan serve and head over to http://localhost:8000/register to create an account . The accounts creation page looks like this

Fill the form and hit submit. Oops, we see an error.

Registration Error

Let's fix it. Simply open up /App/Http/Controllers/Auth/RegisterController.php and add the following lines. To the array in the validator method add this line

'username' => 'required|max:255',

To the array in the create method, add this line

'username' => $data['username'],

That done, save and refresh the page and you should see this page.

Conviex Registration Page

Simply fill the form and submit and you should see this page

Registration success

Next we should add some users to our system. We can do this by database seeding. To get started, we must run this command

C:\xampp\htdocs\conviex>php artisan make:seeder UsersTableSeeder

This command will create a UsersTableSeeder.php at /database/seeders.

We will create a ModelFactory to help us with test users for our seeder. To do this, open up /database/factories/ModelFactory.php and add the following code

$factory->define(Framework\User::class, function (Faker\Generator $faker) {
    static $password;

    return [
        'name' => $faker->name,
        'username' => $faker->username,
        'email' => $faker->safeEmail,
        'password' => $password ?: $password = bcrypt('secret'),
        'remember_token' => str_random(10),
    ];
});

We must then add this line to the newly created file. This will create 10 users.

factory(Framework\User::class, 10)->create();

Then open up the DatabaseSeeder.php file at /database/seeders and add this line to the handle method.

$this->call(UsersTableSeeder::class);

Then run this command

C:\xampp\htdocs\conviex>php artisan db:seed

Great! Now we are registered and we have test users for our conversations system.

Talking to Others.

Let's have a look at our users! We need a page where we can look up all the available users and start a convo kind of like a phone's directory. Open up src/Services/Web/routes/web.php and add this route

Route::get('/users', 'UserController@index');

Let's create the UserController. Simply cd into the /vendor/bin and run

 C:\xampp\htdocs\conviex\vendor\bin>lucid make:controller UserController web

We'll also need a feature that provides the users for us. Let's create the ListUsersFeature. Run this command to create the ListUsersFeature.php.

 C:\xampp\htdocs\conviex\vendor\bin>lucid make:feature ListUsersFeature web

Let's open up the controller and serve the ListUsersFeature. Add this line to the index method in src/Services/Web/Http/Controllers/UserController.php

    return $this->serve(ListUsersFeature::class);

Awesome! Let's open up src/Services/Web/Feature/ListUsersFeature.php and add some code.

First, import the Eloquent User model

use Framework\User;

Then add these lines to the handle method.

$users = User::all();

$data = [
    'users' => $users
];

return view('app.user.user-index', [
    'data' => $data
]);

For a more attractive user interface, let us generate avatar images automatically for our conversation system users. To do this let's get the Laravolt\Avatar composer package. Open up composer.json and add this line to the require JSON object.

    "laravolt/avatar": "^1.8"

Next run this command to install our package

 C:\xampp\htdocs\conviex>composer update

We then need to register the package at /config/app.php. Simply add this line to the providers array.

 Laravolt\Avatar\ServiceProvider::class,

Next, add this line to the aliases array.

'Avatar' => Laravolt\Avatar\Facade::class,

Then we just have to add a method to generate our avatar to our User model.

 /*
  * Returns an avatar image based on a users name.
  *
  * @return { String }
  */

 public function getUserAvatar($size = 128)
 {
     $avatar = Avatar::create($this->name)->setDimension($size)->setFontSize(10)->setShape('square')->toBase64();

     return $avatar;
 }

That's awesome! We just need to do one more step to see all our users show up in our browser. Create a file called user-index.blade.php at /resources/views/app and add these lines to the file.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3>
                        Conviex Users
                    </h3>
                    <p class="small text-muted">Tap the message button to start a conversation.</p>

                </div>

                <div class="panel-body">
                    <section class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <td><span class="sr-only">Avatar</span></td>
                                    <td><b>Name</b></td>
                                    <td><b>Username</b></td>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($data['users'] as $user)
                                @if ($user and $user->id != Auth::id())
                                <tr>
                                    <td> <img class="img img-responsive img-circle" src="{{ $user->getUserAvatar(30) }}" alt="{{ $user->getFirstName() }} avatar"> </td>
                                    <td>{{ $user->getFirstName() }}</td>
                                    <td>{{ $user->username }}</td>
                                    <td>
                                        <a href="{{ url(route('message', $user->id)) }}" class="btn btn-xs btn-primary" data-toggle="tooltip" data-placement="top" title="Start a conversation with {{ $user->name }}">
                                            <i class="glyphicon glyphicon-envelope" style="font-size: 18px;"></i>
                                        </a>
                                    </td>
                                </tr>
                                @endif
                                @endforeach
                            </tbody>
                        </table>
                    </section>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Now, simply had over to http://localhost:8000/users and you should see this.

Conviex Users List

Conclusion

In this post, we revisited some important content from our previous post in this series. We created a ModelFactory instance, seeded our database with test users, created the ListUsersFeature to help us see all users we can start a conversation with.

Our next post will be really awesome, guys! We'll do so much new stuff. We will focus on showing each conversation involving ourselves. We will also create some new methods and so much more.

Keep on the edges of your chairs. The next installment will be steaming hot.

Curriculum



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Congratulations @creatrixity! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of posts published

Click on any badge to view your own Board of Honor on SteemitBoard.

To support your work, I also upvoted your post!
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

Upvote this notification to help all Steemit users. Learn why here!

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @creatrixity I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Coin Marketplace

STEEM 0.16
TRX 0.15
JST 0.028
BTC 57658.56
ETH 2273.22
USDT 1.00
SBD 2.46