Removing /public from URL

There are couple of ways for doing this:

  1. htaccess method:
    • move the htaccess file from public folder to the root folder
    • rename server.php to index.php
    • that’s it really!
    • The biggest flaw using this way is that .env file becomes accessible to web.
  2. Using Content Moving:
  3. Changing the document root on the server

Reference:

http://tutsnare.com/remove-public-from-url-laravel/

Find this out:

https://laracasts.com/discuss/channels/laravel/removing-public-from-url-where-does-laravel-get-the-base-url-from?page=1

 

Advertisements

Laravel folder structure

  • Routes – /app/Http/routes.php
  • Controllers – /app/Http/Controllers
  • Models – /app/modelname.php
  • Views – /resources/views/
  • Database
    • Migrations – /database/migrations
    • Seeds – /database/seeds
    • sqlite database storage – /storage
  • APP URL & DB Configuration – /.env
  • Composer file -/composer.json
  • All downloads by composer – /vendor/
  • App Configuration, Providers & Aliases – /config/app.php

CodeIgniter

Notes:

  1. CodeIgniter is MIT licensed which means it’s FREE.
  2. Here is the website for CodeIgniter https://www.codeigniter.com/
  3. PHP 5.6 > & mysqli and pdo drivers needed
  4. This is very lightweight & easy to install.
  5. Download the latest version from the website. (I’m using 3.1.0)
  6. Check your current version:
    • echo CI_VERSION;

  7. Unzip & copy the files to your web server
  8. Set the app url in application/config/config.php
  9. Set the database parameters in application/config/database.php
  10. If you want to have more security, change the system and application folders to something else and indicate them in index.php in the root folder. System & application folders should never be accessible to web
  11. CodeIgniter doesn’t have a template enginer. You’ll need to learn the templating code like blade in Laravel if you want a template enginer. CodeIgniter uses php blocks instead. Although there is a template parser optionally available.
  12. Application Flow:
    • CI - application flow
  13. MVC structure but fairly loose approach. You can ignore models & build application using controllers & views.
  14. CI lets you use existing scripts & it doesn’t require you to use command line.
  15. URI segments – example.com/class(controller class)/function(class function)/ID (any parameter passed)
  16. Removing the index.php – http://www.codeigniter.com/user_guide/general/urls.html#removing-the-index-php-file
    1. create .htaccess file in the root folder and add following code
      • RewriteEngine on
        RewriteCond $1 !^(index\.php)
        RewriteRule ^(.*)$ index.php/$1 [L]

  17. You can add url suffixes, just to pretend they are .html or .xyz
  18. Query strings in the URL are also possible – http://www.codeigniter.com/user_guide/general/urls.html
  19. Controllers: all the controllers are stored in this folder
    • Create a file name World.php in the controllers folder
    • name the class World similar to the welcome (Welcome.php) controller.
    • if you have not removed or redirected index.php, the url you need to access is appurl/index.php/world
    • URI segments can be passed to methods:
    • example.com/index.php/products/shoes/sandals/123
    • public function shoes($sandals, $id) {echo $sandals; echo $id;} will echo Sandals & 123 on the page.
    • Default controller – can be set in /application/config/routes.php
  20. Remapping methods:
  21. output method
  22. private or protected methods will not be served to the public
  23. Views:
    • views stored in /application/views. Just with .php extension
    • called with $this->load->view(“viewname”);
    • headers & footers can be put in different views and can be called all at ones in an order.
    • Adding data to the views:
      • sending data in arrays as parameter to the view. Eg: $this->load->view(‘viewname’, array(“country”=>”Australia”,”city”=>”Melbourne”));
      • Calling the variable with key names in the views. Eg: $country, $city
      • foreach loops can be used
    • Returning data to a string
      • Setting the third parameter to “TRUE” will return all the view data to a string.
      • Eg: $string=$this->load->view(‘viewname’,”, TRUE);
    • View eg:
    • <!DOCTYPE html>
      <html>
      <head>
      <meta charset=”utf-8″>
      <title>My World</title>
      <style>
      body{
      font-family:sans-serif;
      }
      </style>
      </head>
      <body>
      <section>
      <? foreach ($world as $country) {?>
      <h3><? echo element(‘country_name’,$country); ?></h3>
      <ul>
      <? foreach ($country[‘cities’] as $city) { ?>
      <li><?= $city[‘city_name’]; ?></li>
      <? } ?>
      </ul>
      <? } ?>
      </section>
      </body>
      </html>

  24. Models:
    • Models work with information in your database
    • Model classes will have a function to insert, update and retrieve data from DB
    • Models are stored in /application/models/
    • Class name should always start with capital letter
    • file name must match class name
    • Loading model:
      • $this->load->model(“model_name”);
      • ones the model is loaded, you’ll get access to all methods using an object with the same name as your class.
      • $this->model_name->method();
      • you can assign a different name to the object with the second parameter. Eg: $this->load->model(“model_name”,”obj_name”);
    • Getting results from DB:
      • Database parameters needs to be set already in /application/config/database.php or can be manually set using $config[‘database’] etc
      • you have to autoload database libraries in /application/config/autoload.php. Eg: $autoload[‘libraries’]=array(‘database’);
      • Model code: public function get_all(){
        $query=$this->db->get(‘country’);
        return $query->result();
        }
      • Controller code: $this->load->model(“World_model”);
        $data[‘data’]=$this->World_model->get_all();
        $this->load->view(‘worldview’,$data);
      • View code: <?php foreach ($data as $key => $value) {
        echo “<h2>”.$value->name.”</h2>”;
        ?>
      • Check all the functions available for Database queries
    • Database query builder:
      • Using query builder pattern gives a simplified means of retrieving data. Instead of writing the entire query ‘select …’, could use get().
      • class World_model extends CI_Model {
        public function __construct(){
        parent::__construct();
        }
        public function get_all(){
        $query=$this->db->get(‘country’);
        $world=[];
        foreach ($query->result() as $row)
        {
        $cities=$this->get_cities($row->country_id);
        $world[]=array(‘country_id’=>$row->country_id,
        ‘country_name’=>$row->name,
        ‘cities’=>$cities,
        ‘created_at’=>$row->created_at,
        ‘updated_at’=>$row->updated_at);
        }
        return $world;
        }
        public function get_cities($country_id){
        $query=$this->db->get_where(‘city’,array(‘country_id’=>$country_id));
        $cities=[];
        foreach ($query->result() as $row)
        {
        $cities[]=array(‘city_id’=>$row->city_id,
        ‘city_name’=>$row->name,
        ‘created_at’=>$row->created_at,
        ‘updated_at’=>$row->updated_at);
        }
        return $cities;
        }
        public function get_countries(){
        $query=$this->db->get(‘country’);
        return $query->result();
        }
        }
      • Learn more here http://www.codeigniter.com/user_guide/database/index.html
  25. Helper functions:
    • helpers can be stored in /applications/helpers/ folder
    • Multiple helpers can be loaded
    • helpers can be autoloaded for global usage
    • Once you’ve loaded the Helper File containing the function you intend to use, you’ll call it the way you would a standard PHP function.For example, to create a link using the anchor() function in one of your view files you would do this: <?php echo anchor(‘blog/comments’, ‘Click Here’);?>
    • Array Helper
      • eg: echo $array_name[‘hello’] can be written as echo element(‘hello’, $array_name);
    • http://www.codeigniter.com/user_guide/helpers/index.html
  26. Using libraries
  27. Using CodeIgniter Drivers
    • Drivers can be loaded like all $this->load->driver(“driver_name”);
    • Stored in libraries folder under driver_name directory
  28. Core classes can be extended or replaced
  29. Hookes:
  30. Common functions & compatibility functions
  31. Routing:
    • Wildcard routing
      • Setting your own routing rules is possible & it must be defined in /application/config/routes.php, to an array $route.
    • Regular expressions:
      • Eg:  $route[‘products/([a-z]+)/(\d+)’] = ‘$1/id_$2’;
    • Call backs:
      • Eg: $route[‘products/([a-zA-Z]+)/edit/(\d+)’] = function ($product_type, $id{         return ‘catalog/product_edit/’ . strtolower($product_type) . ‘/’ . $id};
    • Using HTTP verbs –
      • Eg: 
        • $route[‘products’][‘put’] = ‘product/insert’
        • $route[‘products/(:num)’][‘DELETE’] = ‘product/delete/$1’;
    • There are few reserved routes like default_controller, 404_override, translate_uri_dashes
      • The reserved routes must come before any wildcard or regular expression routes.
  32. Error handling:
  33. Caching:
    • performance can be achieved by caching pages
    • you can set the time
    • Eg:  $this->output->cache($n);
    • Deleting cache is also possible with a call.  Eg: $this->output->delete_cache(‘/foo/bar’);
  34. Profiler:
  35. Running with CLI:
    • You can call the controllers on command line as well
  36. Running multiple applications in the same installation is not possible unless you copy all the folders like config, controllers into each sub directory
  37. Environment:
    • By default, CodeIgniter comes with the environment constant set to use the value provided in $_SERVER['CI_ENV'], otherwise defaults to ‘development’. At the top of index.php in roote folder, you will see: define(‘ENVIRONMENT’, isset($_SERVER[‘CI_ENV’]) ? $_SERVER[‘CI_ENV’] : ‘development’);
  38. Security:
    • URIs should only contain the following:
      • Alpah-numeric text
      • ~, %, ., :, _, -, space
      • hash_pbkdf() is for versions of php below 5.5 for password hashing
  39. Create Form:

My Github Repo:

https://github.com/sainag/CodeIgniter_World

Laravel Tutorial 2

Database configuration:

  • Specify the database being used in config/database.php
  • If you’re using sqlite, create an “database.sqlite” file in either databses or storage. We do not need to edit the “.env” file
    • Setting the path for database.sqlite
      • folder names are referenced with “_path” Eg: storage folder as “storage_path()”, database folder as “database_path()”
      • If the file is in the storage folder then you can write “storage_path(‘database.sqlite’)”, else if it is in the database folder then you can write “database_path(‘database.sqlite’)”
  • If you’re using mysql change the authentication details and edit the “.env” file

Migrations:

First we will need to set up database schema.

  • Migrations are version control for databases
  • Usually you create tables using GUI but these migrations help you create tables in the app. It will help the team to work with tables without using GUI but with code
  • Creating a migration doesn’t create the table. It will need to be migrated to get the tables created
  • You want to make a migration: Check these commands
    • php artisan make:migration nameofmigration
    • php artisan migrate — This will create the tables  in the database
  • You can roll back using Down functions in the migration class

Reference:

Seeding:

  • Laravel includes a simple method of seeding your database with test data using seed classes. All seed classes are stored in database/seeds. Seed classes may have any name you wish, but probably should follow some sensible convention, such as UsersTableSeeder, etc.
  • Adding some data to the tables for viewing something on the browser
  • Use “php artisan make:seeder UsersTableSeeder”
  • Add insert statements in the run method
  • DB::table(‘words’)->insert([ ‘word’=>’Modest’, ‘meaning’=>’Refusing to take any credit’, ‘language’=>’English’ ]);

  • Running Seeders:
    • php artisan db:seed
    • php artisan db:seed –class=UsersTableSeeder (for sepcific seeders)

Model:

  • To work with our database we need models
  • php artisan make:model User
  • model gets created in /app folder – ‘user.php’

Controllers:

  • To start hitting the browsers we need to set up some Controllers and Routes to point to them.
  • php artisan make:controller UsersController
  • controller gets created in /app/Http/Controllers folder

Routes: 

https://laravel.com/docs/5.4/routing

  • Routes location:
    • Laravel 5.2.45
      • app/http/routes.php is the main routes file
    • Laravel 5.4.26
      • /routes/web.php is the main routes file
    • User php artisan –version” to know version of Laravel
  • You can return a view by writing
    • Route::get(‘/’, function () { return view(‘welcome’); });
  • You can return resources from controller
    • Route:resource(‘users’,’UsersController’);
  • command prompt – php artisan route:list to view all the routes
  • You can do nested resources (joining tables)
  • Calling a function in a controller:
    • Route::get(‘about’,’UsersController@index’);
    • you should have index function in the UsersController.php page
      • public function index(){ return ‘Welcome to My Dictionary’; }
      • this will return the welcome message string when you navigate to /app/about
    • Returning a view:
      • Do not worry about the extension of the view or path of the view while referencing a view
      • can name the view like ‘folder.view’
    • Routing a model
      • Route::model(‘words’,’Word’);
  • app/users – which got both GET & POST works everywhere except Firefox

Route Model binding:

  • https://laracasts.com/series/laravel-5-fundamentals/episodes/18
  • route() helper function with a named route
  • routes.php ‘explicit binding’ –
    • Route::bind(‘words’, function($value) {
      return App\Word::where(‘userid’,$value)->first();
      });
    • which lets you use App/users/1 and shows all the details on the page

Reference:

Views:

  • To have consistent layouts across follow –  https://laravel.com/docs/5.0/templates#blade-templating
  • Reading & showing data is done – you don’t need to write any database queries to get the data from the database – it is done by Laravel

Reference:

Create/Edit/Delete:

Create:

  • Creating a “Create User” link in the index.blade.php file
  • {{ HTML::linkRoute(‘create’, ‘Add Word’) }}
    • In Laravel 5.0 HTML & Form helpers not added by default anymore
    • add “laravelcollective/html” in the required array of the composer file
    • Add the following in config/app.php file
      • add providers – “Collective\Html\HtmlServiceProvider::class”
      • add alliases – ‘Form’ => Collective\Html\FormFacade::class‘Html’ => Collective\Html\HtmlFacade::class,
    • https://laravelcollective.com/docs/5.2/html

Create & Edit View:

  • create.blade.php & edit.blade.php needs to be created
  • <!-- /resources/views/projects/create.blade.php -->
    @extends('app')
     
    @section('content')
        <h2>Create Project</h2>
     
        {!! Form::model(new App\Project, ['route' => ['projects.store']]) !!}
            @include('projects/partials/_form', ['submit_text' => 'Create Project'])
        {!! Form::close() !!}
    @endsection
     
    <!-- /resources/views/projects/edit.blade.php -->
    @extends('app')
     
    @section('content')
        <h2>Edit Project</h2>
     
        {!! Form::model($project, ['method' => 'PATCH', 'route' => ['projects.update', $project->slug]]) !!}
            @include('projects/partials/_form', ['submit_text' => 'Edit Project'])
        {!! Form::close() !!}
    @endsection
  • Form View: /_form.blade.php
    • {!! Form::label(‘name’, ‘Name:’) !!} {!! Form::text(‘name’) !!}

      {!! Form::label(‘slug’, ‘Slug:’) !!} {!! Form::text(‘slug’) !!}

      {!! Form::label(‘completed’, ‘Completed:’) !!} {!! Form::checkbox(‘completed’) !!}

      {!! Form::label(‘description’, ‘Description:’) !!} {!! Form::textarea(‘description’) !!}

      {!! Form::submit($submit_text) !!}

  • Fixing mass assignment exception by addin – protected $guarded = []; to model “user.php” in app folder
  • You can start adding users
  • Note – If the primary key is not ‘id’ for a table it won’t update. You’ll have to change the the primary key in your model (Eloquent ORM (Object Reference Model)). Eg -> protected $primarykey=’userid’;
  • CRUD operations done
  • Flash Messages:
    • These are the messages that can be shown after a successful request

Things to do:

  • How to remove /public/app etc and make it /app without giving access to .env file?
  • How to add bootstrap & styling?
  • How to add JS if required?
  • How to move this localhost built app to a new server?

Whole Project Reference:

Github Repo: