Laravel 5: Eloquent Properties

Laravel 5: App Folders In a Nutshell

App Folders In a Nutshell

Here, you will find some basic explanation as to what are all these folders in directory \app are for.

Console Commands allow to define custom command to be used in Laravel console called Artisan.
This command can do designed by you task.
It is great for defining commands you can then use in scheduling etc.

Event is a predefined activity
Event described here is powered by Event object.
There are other event-like constructs in Laravel, like:

  • Eloquent events
  • Queue jobs – see them as listeners combined with events
  • Schedules – these are events powered by cyclical, Chron-based repetitive pattern

Event is a trigger call, that results in some response action.

sample:
event: order is completed
response (by listener): email notification


Listeners are responding scripts to event.

If you fire and event, as described just above, there are some scripts designed to respond.

example (in addition to one above):
event: user logs in
listener: log user login time and IP etc. to some log or database table


Subscribers is a construct, that allows you to create more than one Listener in single class file.

For me it seems like overkill.

I’d rather place my Listeners inside of sub-directories, as many levels down as needed and follow single responsibility coding rule, than try to clunk Listeners together inside of some surreal ‘animal farm’.

But sometimes, it makes sense to group a few Listeners thematically linked into a single file.
e.g.: login eventing: onUserLogin, onUserLogout …etc.
But then, you start having code doing same stuff in different places (different \app folders) – can get confusing.


This is a totally different kind of events.
They are fired by Eloquent itself.
Of course, you could fire your own events, but you’d have to check e.g. results of query etc.
With Eloquent, you do not have to bother. It is handed to you on a golden platter.


Observers are in a way similar to Subscribers, but ‘only in a way’.
I strongly recommend using Observers.

Reason:
All that Eloquent eventing code goes inside of Service Provider boot() method.
So, some Providers can get awfully crowded.
Observer allows to move all that code elsewhere and replace it with just one line of descriptive code.
This makes code a lot more readable.

Jobs have a lot in common with events/listeners.
They are designed to perform same, or at least similar task.
They even work in a very similar way and both can utilize Queues.

There are some differences thou.

#1.
Job
: helper function dispatch() (job trigger), can call only one job.
Event: helper function event() (event trigger) calls event class, which can call into action more than one listener

job-event
#2
Job Scope

Jobs seem to be created to unload code from Controllers and make them lighter, and seem to be meant for bigger tasks, than Events.

#3
Queue Scope
Events: all you can really do, is that you can enable queuing and that is pretty much it.
Jobs: It is easier to use different connections, like: database, beanstalkd, sqs etc. plus you have bunch of other functionality to mold queue to fit your needs.

So, if you have more than one task to accomplish, use Events, otherwise use Jobs, especially, if you want to unload Controller and push some code into external files – for better readability.

Eloquent scopes are nothing more than a method to append some code to SQL query.

Example:
Lets say, that you want to make sure, that draft posts and disabled posts are never going to be shown up front.
You can use Scope to add by default constrain preventing selection of these posts.

In other words.
You do not have to opt-out to get collection without drafted and banned posts.
You get that by default.
You have to opt-in to get these banned and drafted posts, e.g. for display in the backend.

Library

This is not Laravel standard issue part.

Remember good ole’ global functions from early days?

Functions tucked into some file, required in some application_top.php and available everywhere you needed them.
That is how you can use Library.

So, how to set it up.

Create folder Library inside of folder app/.
Create any number of helper classes you need

e.g. Sorting class, for generalised sorting tools for table listed columns.

How to use it

a. ‘new up’ as you would always do:

b.  automatic resolution (injection) using IoC container:

See this link for more.

This can be very useful, especially in highly compartmentalised project, where all sections may need repetitive functionality – like list sorting by column.

 

Services

This is not Laravel standard issue part.

Also, you may put some task specific code.

This code can do some job for you, so you pull easily result of that job into blade directly, or inject it to Controller via method injection.
This is how you do it in blade directly:

Sometimes, when you have to test your app.
For that you need some data in your database.
Problem is, that when you start developing, usually your database is quite empty.

Seeder is a way to help you.
Especially when used together with standard issued by Laravel library Faker, which can help you to generate thousands of realistic records for testing.

Testing
Seeders are great during unit testing.
You can add DB seeding code to your testing code, add some roll-back utility (or use built-in) and have your database turned back to state before testing for any future testing.
Above is great to avoid skewing testing results due to data difference.

Providers

This folder has to do with:

In general, Service Container is like a factory, which builds for us objects with all dependencies injected into object.
Actually, there is a code design pattern, which is being used just for that – building objects with dependencies.
And this is pretty much, what it is.

Service Provider, to some extent, reminds me of Windows registry.
It is a place to register all important services, like for instance:

  • service container bindings,
  • event listeners,
  • middleware,
  • even routes etc.

See links above in this section.

This is Laravel native way to do Cron tasking.
And much better I must say.
Click ‘Schedules’ link above for more details.
There is an added bonus there for all those, who code on Windows and use some form of LAMP emulator, like XAMPP.
That bonus, I mentioned, is a very detailed way (with images), how to setup Cron-like behavior on Windows, using Windows ‘Task Scheduler’.

Migrations

Migrations allow automation in creating tables.

It is also table version control, that allows to see, to what is being done to table/database over the time.

More here and here.

Mail
config and .env

All configuration values are in config\mail.php file.
It can be overridden in .env file.

Guzzle HTTP Library

You need this library.
Run this code – if you have it already, it’ll just get updated.

generate mail class

There is Artisan command doing it for us:


Detailed example on how to put email code together can be found on this page.

Routes, in general, are like a switchboard.
Request comes in and routing system directs it into a proper resource, that is equipped to handle it.

Middleware provide a convenient mechanism for dealing with HTTP requests entering your application (before middleware), or responses leaving it (after middleware).

Best example of middleware is authorization.

More here and here.

Controllers can group related request handling logic into a single class.
This is a place, where all functionality residing elsewhere is pulled into to serve incoming request.

HTTP request, is exactly what the name suggest.
It is a request sent by client to server for some resource.
It could be anything: text, image, data processing, data stored in database etc.
Of course there is more to it, but in general, above covers it.

Models

These are classes which allow data data flow to and from database tables.

Important:
Read a bit below abut Repositories.
Not all code interacting with Database goes into Model – especially if you are using Eloquent ORM.
And definitely, you do not want to interact with Database (even via Model) from within Controller.
Why?
Well, there is that thing called ‘loose coupling’.
Read about Repos below.

Even best coded app will get in trouble and generate errors.
Your app will have to be able to recover from errors and be able to tell you about them, so you can (possibly) fix them.

Policies are classes that organize authorization logic around a particular model or resource.
For instance, Post model may have PostPolicy class with all you need to authorize post updates, posting, deletion. Naming is arbitrary. It is up to you.
Policies are stored in catalog:  app/Policies/

Repositories help to make your app future-proof, by loosely coupling your controllers to database logic, e.g. Eloquent, so you can switch your data storage anytime without affecting rest of your app.

See here how it is done.

Read and watch more here – especially first one:

Laravel 5: Eloquent Methods

Laravel 5: Eloquent Relationships

Laravel 5: Background processes checklist

Laravel 5: Background processes checklist.


Laravel project involves a bit more than PHP code.
Here is the list, what you need to remember, when setting your app.


Checklist: Windows Environment Variable Path

Some software must (should) be added to Windows environment Variable Path.

Read more here.

Also, see this sample of ‘variable value’ in this text file.

Checklist 1: cron

Setup Cron, or for Windows (e.g. for dev) equivalent pseudo-Cron using task scheduler.
More here.

Difference is in: “Go to TAB: Actions, and click ‘New’ button” #2.

Each Laravel project needs separate cron setup in Windows task.
E.g. in example (link here above) I have: U:\www\la4\artisan.
Above path will make cron run only for project located in /la4 folder.
So, each folder/project needs own cron to work.

Above does not apply to Redis.
Explanation above apply to Windows dev setup.

Also see screenshots with how to setup Windows task: zip-file

 


Checklist 2: Redis

You need to install and start Redis server – if you are using it.
And since Redis can help in queues, cache, broadcasting and as database – it is worthwhile to install it.

For Linux, see here.

For Windows, see here and scroll down to: “setup Windows task”.
It uses same methodology as Cron. Anyway, all links are there.

Dependencies:

  • ioredis
  • predis

Also see screenshots with how to setup Windows task: zip-file

 


Checklist 3: Queues

If you are using queues other than ‘sync’, e.g. QUEUE_DRIVER=redis, then you need php artisan queue:listen command running. Eventually, you may use something like php artisan queue:work –sleep=3 –tries=3 .

For quick testing, you can run it in your console/command prompt, but to have it run all the time – also for dev, it is better to have daemon on Linux/Unix (OSX), or Task on Windows.

Linux setup – see here.

Windows setup – see here.

There is some difference thou to “Windows setup” description above:

Difference is in: “Go to TAB: Actions, and click ‘New’ button” #2.

Each Laravel project needs separate cron setup in Windows task.
E.g. in example (link here above) I have: U:\www\la4\artisan.
Above path will make cron run only for project located in /la4 folder.
So, each folder/project needs own cron to work.

Above does not apply to Redis.
Explanation above apply to Windows dev setup.

NOTE:
Queues daemon should be run and overseen by supervisor script.

Also see screenshots with how to setup Windows task: zip-file

 


Checklist 4: Sockets

Nice read is here. Thanks Gergely.

Also read here.

Dependencies:

  • socket.io
  • express (possibly)
  • node.js
way 1:
Note:
Use this way for development purposes, e.g. when you develop in Windows and you want to have it on constantly.
For production on Linux server use Supervisor.
This way will not react to any process dropped. Supervisor will reinstate such process.

Put inside of method schedule() of :

… this code:

Here is socket.js script:

Cron must be on for this to work.

way 2:

First we need Forever script.
It is somewhat like Supervisor, just for node scripts only:

Now again we use schedule, so cron must be up:

If you do not like Forever, but do not want to go for Supervisor, try PM2.

 

way 3:

Use Supervisor.
It will work on Linux server, not on Windows.
For windows, see above.

It is a script written in Python. It allows to control also other processes than node.js.
More here.

Sample Supervisor config might look like this (it should be placed at /etc/supervisor/conf.d/myapi.conf):

Checklist 5: config and .env

Make sure all settings in .env file are taken care of, like:

  • APP_DEBUG
  • APP_LOG_LEVEL
  • and the rest
Checklist 6: JS, CSS, NPM dependencies, SASS etc
Up to Laravel 5.3 … you need gulp
Laravel 5.4 – Laravel mix (webpack)

Run:

and

Also read this.

Laravel 5.4
.env constant

.env constant be set properly:

Dusk has different test directory.
Dusk does not come in a package and has to be installed
step 1: console composer

step 2: service provider

Register the provider within the register() method of your app\Providers\AppServiceProvider, like this:

install dusk

Next, run the dusk:install Artisan command:

More about Dusk – try Laravel docs and articles on this page.

Laravel 5.0 – 5.3

Up to Laravel 5.4 browser testing was done using Integrated Package.
Use link just above for detailed info.

Videos:

Laracast videos (Intermediate series: “2015-03-23-Intuitive Integration Testing“) are here:

  • video: Introduction and General Usage
  • video: Laravel and Integrated
  • video: Database Transactions
  • video: Example Workflow and Custom Methods
  • video: Selenium
  • video: Testing APIs
Installation:

More about installation etc. – here.

Usage Notes:
in windows you may do: vendor\bin\phpunit
note how slashes go!
command prompt expects backslash, not forward slash (like in most
tutorials done on Linux, or Apple, or VM (like HomeStead)

 

Socket.Io – Working Chat and General Stuff

Socket.Io – Working Chat and General Stuff


Socket.io allows for PHP based system to have server pushing data to client without request from client.

Most of that stuff below needs node.js installed on your server.

If you work on Windows just get Windows installer and add node to your Environment Variable path, to make it global.

Similar operation describing registering Composer with EV path is described here.


Socket.Io
Checking version

Same way you can check all stuff installed via np, like: express, ioredis etc.

Installation

Socket.io can be downloaded from here.

It can be installed using node.js npm, like this:

It is good to use ‘–save’ flag to add socket.io to dependencies list in your project package.json file, to keep it up to date with other stuff you are using, or you are about to use.

Usual socket project structure

Socket client

You need a socket.io client, which your project will pull into user’s browser
Something like:

If you do not want to use socket.io CDN (content delivery network) hosted client script, you can download version from here and serve it from your own server, or some other CDN.

Socket server worker

This is usually an index.js file, which is being activated via console command:

This file is a place where you bootstrap and fire all needed elements, like:

  • express framework
  • socket.io and all its channels, connections and broadcasting
  • html/template file (called, when accessing defined port)
  • define a port app is going to be listened on
  • etc.

When bootstrap is neatly tied, you can listen to your app in browser, by listening to defined port like this:

 

Sample Chat

Socket.io home page have chat demo here.

Unfortunately demo does not work.

In downloadable package below, you will find fixed version of that chat.
Of course, full credit goes to creators – I just fixed  few little things.

Edit 2018-03-18: demo works now and they added nice whiteboard.

zip

In archive you will find a drop-in package.
What it means is that all you have to do is:

  1. unzip
  2. drop content of folder /b8 (in archive) to your localhosted location
  3. change ‘b8’ in index.html file to your own localhosted location/domain, e.g. /mychat
  4. you need internet access (dependencies: botstrap, socket client, jquery)
  5. node dependencies: socket.io and express are already in zipped package
  6. open command prompt (windows) or console and go inside of your ‘mychat’ directory (or some other you are using)
  7. type is: node index.js – keep console open
  8. navigate in your browser to: mychat:3000

… and you have working chat open.

Now you can open another window with chat (or two) and see how posted stuff gets passed via sockets between browser windows. Same it would work between people in remote locations.

Here, you can find some nice socket.io cheat-sheet. Thanks Alex.
Just is case, it is also accessible here: socket-cheatsheet

 


Redis

If you wish to store some data, you can use Laravel’s Swiss army knife: Redis (queues, broadcasting, cache, data storage etc.)
More about Redis – here.

 


Redis.Js

There is also Redis API (client) called Redis.Js, that is a great way to work with Redis from within Socket.Io code.
You can find it here.

When installing, it is good to add it as dependency to your package.json like this (note –save):

This will update your package.json.

You need to have Redis installed on your system to use above wrapper (API)!
Other Redis clients

Find the all here.

Also, you may look at ioredis instead of redis.js

 


Express JS Framework

You will need this JS framework to work with sockets.

You can install it like this:

Again, ‘–save’ will add it to package.json as dependency.

 

Check number of queries run

Check how many queries Laravel runs.

Sometimes you mat want to see how many queries Laravel has just run.

It may come handy, when using ‘eager loaded’ relations.

Just to make sure, if you are really ‘eager loading’ stuff.

Also, it is handy to see query as it was passed to SQL server in raw SQL code.

Of course, we have helper function toSql(), but in some cases this method is better:

And this is a result you will get on the screen:

Above example shows, that we have run 2 queries.


Of course you can accomplish this in many different ways, including systemic.
But I prefer surgical placement of testing tool, where I need it.


You can also read more here: