- Create a new laravel project:
1composer create-project --prefer-dist laravel/laravel laravel-blog-tutorial
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255teddy@teddy-K43SJ:~/Documents/works/laravel$ composer create-project --prefer-dist laravel/laravel laravel-blog-tutorialYou are running composer with xdebug enabled. This has a major impact on runtime performance. See https://getcomposer.org/xdebugInstalling laravel/laravel (v5.3.16)- Installing laravel/laravel (v5.3.16)Loading from cacheCreated project in laravel-blog-tutorial> php -r "file_exists('.env') || copy('.env.example', '.env');"Loading composer repositories with package informationUpdating dependencies (including require-dev)- Installing vlucas/phpdotenv (v2.4.0)Loading from cache- Installing symfony/polyfill-mbstring (v1.3.0)Loading from cache- Installing symfony/var-dumper (v3.1.8)Downloading: 100%- Installing symfony/translation (v3.1.8)Downloading: 100%- Installing symfony/routing (v3.1.8)Downloading: 100%- Installing symfony/process (v3.1.8)Downloading: 100%- Installing psr/log (1.0.2)Loading from cache- Installing symfony/debug (v3.1.8)Downloading: 100%- Installing symfony/http-foundation (v3.1.8)Downloading: 100%- Installing symfony/event-dispatcher (v3.2.1)Loading from cache- Installing symfony/http-kernel (v3.1.8)Downloading: 100%- Installing symfony/finder (v3.1.8)Downloading: 100%- Installing symfony/console (v3.1.8)Downloading: 100%- Installing swiftmailer/swiftmailer (v5.4.4)Downloading: 100%- Installing paragonie/random_compat (v2.0.4)Downloading: 100%- Installing ramsey/uuid (3.5.2)Downloading: 100%- Installing jakub-onderka/php-console-color (0.1)Loading from cache- Installing jakub-onderka/php-console-highlighter (v0.3.2)Loading from cache- Installing dnoegel/php-xdg-base-dir (0.1)Loading from cache- Installing nikic/php-parser (v3.0.2)Downloading: 100%- Installing psy/psysh (v0.8.0)Downloading: 100%- Installing nesbot/carbon (1.21.0)Loading from cache- Installing mtdowling/cron-expression (v1.1.0)Loading from cache- Installing monolog/monolog (1.22.0)Downloading: 100%- Installing league/flysystem (1.0.32)Loading from cache- Installing symfony/polyfill-util (v1.3.0)Downloading: 100%- Installing symfony/polyfill-php56 (v1.3.0)Downloading: 100%- Installing jeremeamia/superclosure (2.3.0)Downloading: 100%- Installing doctrine/inflector (v1.1.0)Loading from cache- Installing classpreloader/classpreloader (3.1.0)Downloading: 100%- Installing laravel/framework (v5.3.28)Downloading: 100%- Installing fzaninotto/faker (v1.6.0)Loading from cache- Installing hamcrest/hamcrest-php (v1.2.2)Loading from cache- Installing mockery/mockery (0.9.7)Downloading: 100%- Installing symfony/yaml (v3.2.1)Downloading: 100%- Installing sebastian/version (2.0.1)Loading from cache- Installing sebastian/resource-operations (1.0.0)Loading from cache- Installing sebastian/recursion-context (2.0.0)Downloading: 100%- Installing sebastian/object-enumerator (2.0.0)Downloading: 100%- Installing sebastian/global-state (1.1.1)Loading from cache- Installing sebastian/exporter (2.0.0)Downloading: 100%- Installing sebastian/environment (2.0.0)Downloading: 100%- Installing sebastian/diff (1.4.1)Loading from cache- Installing sebastian/comparator (1.2.2)Downloading: 100%- Installing doctrine/instantiator (1.0.5)Loading from cache- Installing phpunit/php-text-template (1.2.1)Loading from cache- Installing phpunit/phpunit-mock-objects (3.4.3)Downloading: 100%- Installing phpunit/php-timer (1.0.8)Loading from cache- Installing phpunit/php-file-iterator (1.4.2)Downloading: 100%- Installing sebastian/code-unit-reverse-lookup (1.0.0)Loading from cache- Installing phpunit/php-token-stream (1.4.9)Downloading: 100%- Installing phpunit/php-code-coverage (4.0.4)Downloading: 100%- Installing webmozart/assert (1.2.0)Downloading: 100%- Installing phpdocumentor/reflection-common (1.0)Loading from cache- Installing phpdocumentor/type-resolver (0.2.1)Downloading: 100%- Installing phpdocumentor/reflection-docblock (3.1.1)Loading from cache- Installing phpspec/prophecy (v1.6.2)Downloading: 100%- Installing myclabs/deep-copy (1.5.5)Downloading: 100%- Installing phpunit/phpunit (5.7.4)Downloading: 100%- Installing symfony/css-selector (v3.1.8)Downloading: 100%- Installing symfony/dom-crawler (v3.1.8)Downloading: 100%symfony/var-dumper suggests installing ext-symfony_debug ()symfony/translation suggests installing symfony/config ()symfony/routing suggests installing doctrine/annotations (For using the annotation loader)symfony/routing suggests installing symfony/config (For using the all-in-one router or any loader)symfony/routing suggests installing symfony/dependency-injection (For loading routes from a service)symfony/routing suggests installing symfony/expression-language (For using expression matching)symfony/event-dispatcher suggests installing symfony/dependency-injection ()symfony/http-kernel suggests installing symfony/browser-kit ()symfony/http-kernel suggests installing symfony/class-loader ()symfony/http-kernel suggests installing symfony/config ()symfony/http-kernel suggests installing symfony/dependency-injection ()paragonie/random_compat suggests installing ext-libsodium (Provides a modern crypto API that can be used to generate random bytes.)ramsey/uuid suggests installing ircmaxell/random-lib (Provides RandomLib for use with the RandomLibAdapter)ramsey/uuid suggests installing ext-libsodium (Provides the PECL libsodium extension for use with the SodiumRandomGenerator)ramsey/uuid suggests installing ext-uuid (Provides the PECL UUID extension for use with the PeclUuidTimeGenerator and PeclUuidRandomGenerator)ramsey/uuid suggests installing moontoast/math (Provides support for converting UUID to 128-bit integer (in string form).)ramsey/uuid suggests installing ramsey/uuid-doctrine (Allows the use of Ramsey\Uuid\Uuid as Doctrine field type.)ramsey/uuid suggests installing ramsey/uuid-console (A console application for generating UUIDs with ramsey/uuid)psy/psysh suggests installing ext-pdo-sqlite (The doc command requires SQLite to work.)psy/psysh suggests installing hoa/console (A pure PHP readline implementation. You'll want this if your PHP install doesn't already support readline or libedit.)monolog/monolog suggests installing aws/aws-sdk-php (Allow sending log messages to AWS services like DynamoDB)monolog/monolog suggests installing doctrine/couchdb (Allow sending log messages to a CouchDB server)monolog/monolog suggests installing ext-amqp (Allow sending log messages to an AMQP server (1.0+ required))monolog/monolog suggests installing ext-mongo (Allow sending log messages to a MongoDB server)monolog/monolog suggests installing graylog2/gelf-php (Allow sending log messages to a GrayLog2 server)monolog/monolog suggests installing mongodb/mongodb (Allow sending log messages to a MongoDB server via PHP Driver)monolog/monolog suggests installing php-amqplib/php-amqplib (Allow sending log messages to an AMQP server using php-amqplib)monolog/monolog suggests installing php-console/php-console (Allow sending log messages to Google Chrome)monolog/monolog suggests installing rollbar/rollbar (Allow sending log messages to Rollbar)monolog/monolog suggests installing ruflin/elastica (Allow sending log messages to an Elastic Search server)monolog/monolog suggests installing sentry/sentry (Allow sending log messages to a Sentry server)league/flysystem suggests installing league/flysystem-aws-s3-v2 (Allows you to use S3 storage with AWS SDK v2)league/flysystem suggests installing league/flysystem-aws-s3-v3 (Allows you to use S3 storage with AWS SDK v3)league/flysystem suggests installing league/flysystem-azure (Allows you to use Windows Azure Blob storage)league/flysystem suggests installing league/flysystem-cached-adapter (Flysystem adapter decorator for metadata caching)league/flysystem suggests installing league/flysystem-copy (Allows you to use Copy.com storage)league/flysystem suggests installing league/flysystem-dropbox (Allows you to use Dropbox storage)league/flysystem suggests installing league/flysystem-eventable-filesystem (Allows you to use EventableFilesystem)league/flysystem suggests installing league/flysystem-rackspace (Allows you to use Rackspace Cloud Files)league/flysystem suggests installing league/flysystem-sftp (Allows you to use SFTP server storage via phpseclib)league/flysystem suggests installing league/flysystem-webdav (Allows you to use WebDAV storage)league/flysystem suggests installing league/flysystem-ziparchive (Allows you to use ZipArchive adapter)laravel/framework suggests installing aws/aws-sdk-php (Required to use the SQS queue driver and SES mail driver (~3.0).)laravel/framework suggests installing doctrine/dbal (Required to rename columns and drop SQLite columns (~2.4).)laravel/framework suggests installing guzzlehttp/guzzle (Required to use the Mailgun and Mandrill mail drivers and the ping methods on schedules (~5.3|~6.0).)laravel/framework suggests installing league/flysystem-aws-s3-v3 (Required to use the Flysystem S3 driver (~1.0).)laravel/framework suggests installing league/flysystem-rackspace (Required to use the Flysystem Rackspace driver (~1.0).)laravel/framework suggests installing pda/pheanstalk (Required to use the beanstalk queue driver (~3.0).)laravel/framework suggests installing predis/predis (Required to use the redis cache and queue drivers (~1.0).)laravel/framework suggests installing pusher/pusher-php-server (Required to use the Pusher broadcast driver (~2.0).)laravel/framework suggests installing symfony/psr-http-message-bridge (Required to use psr7 bridging features (0.2.*).)sebastian/global-state suggests installing ext-uopz (*)phpunit/phpunit-mock-objects suggests installing ext-soap (*)phpunit/phpunit suggests installing phpunit/php-invoker (~1.1)Writing lock fileGenerating autoload files> Illuminate\Foundation\ComposerScripts::postUpdate> php artisan optimizeGenerating optimized class loaderThe compiled class file has been removed.> php artisan key:generateApplication key [base64:rjLfe49t/UHcv74aIu3XHobSXw23qcKpUranTPa2Das=] set successfully.
- Download the ready made laravel blog app from https://github.com/jacurtis/laravel-blog-tutorial. It’s better to donwload in zip file then extract the content in /works/laravel/laravel-blog-tutorial/ directory. Overwrite the existing files and directories.
- Install the laravel component required:
1composer install
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222teddy@teddy-K43SJ:~/Documents/works/laravel/laravel-blog-tutorial$ composer installYou are running composer with xdebug enabled. This has a major impact on runtime performance. See https://getcomposer.org/xdebugLoading composer repositories with package informationInstalling dependencies (including require-dev) from lock file- Removing myclabs/deep-copy (1.5.5)- Removing phpdocumentor/type-resolver (0.2.1)- Removing phpdocumentor/reflection-common (1.0)- Removing webmozart/assert (1.2.0)- Removing sebastian/code-unit-reverse-lookup (1.0.0)- Removing sebastian/resource-operations (1.0.0)- Removing ramsey/uuid (3.5.2)- Removing sebastian/object-enumerator (2.0.0)- Removing nikic/php-parser (v3.0.2)- Installing nikic/php-parser (v2.0.1)Downloading: 100%- Removing classpreloader/classpreloader (3.1.0)- Installing classpreloader/classpreloader (3.0.0)Loading from cache- Removing symfony/polyfill-util (v1.3.0)- Installing symfony/polyfill-util (v1.1.1)Loading from cache- Removing symfony/polyfill-php56 (v1.3.0)- Installing symfony/polyfill-php56 (v1.1.1)Loading from cache- Removing jeremeamia/superclosure (2.3.0)- Installing jeremeamia/superclosure (2.2.0)Loading from cache- Removing league/flysystem (1.0.32)- Installing league/flysystem (1.0.20)Downloading: 100%- Removing psr/log (1.0.2)- Installing psr/log (1.0.0)Loading from cache- Removing monolog/monolog (1.22.0)- Installing monolog/monolog (1.18.1)Downloading: 100%- Removing paragonie/random_compat (v2.0.4)- Installing paragonie/random_compat (v1.4.1)Loading from cache- Removing symfony/polyfill-mbstring (v1.3.0)- Installing symfony/polyfill-mbstring (v1.1.1)Loading from cache- Removing symfony/var-dumper (v3.1.8)- Installing symfony/var-dumper (v3.0.3)Downloading: 100%- Removing symfony/console (v3.1.8)- Installing symfony/console (v3.0.3)Downloading: 100%- Removing psy/psysh (v0.8.0)- Installing psy/psysh (v0.7.2)Loading from cache- Removing swiftmailer/swiftmailer (v5.4.4)- Installing swiftmailer/swiftmailer (v5.4.1)Loading from cache- Removing symfony/finder (v3.1.8)- Installing symfony/finder (v3.0.3)Downloading: 100%- Removing symfony/http-foundation (v3.1.8)- Installing symfony/http-foundation (v3.0.3)Downloading: 100%- Removing symfony/event-dispatcher (v3.2.1)- Installing symfony/event-dispatcher (v3.0.3)Downloading: 100%- Removing symfony/debug (v3.1.8)- Installing symfony/debug (v3.0.3)Downloading: 100%- Removing symfony/http-kernel (v3.1.8)- Installing symfony/http-kernel (v3.0.3)Downloading: 100%- Removing symfony/process (v3.1.8)- Installing symfony/process (v3.0.3)Downloading: 100%- Removing symfony/routing (v3.1.8)- Installing symfony/routing (v3.0.3)Downloading: 100%- Removing symfony/translation (v3.1.8)- Installing symfony/translation (v3.0.3)Downloading: 100%- Removing vlucas/phpdotenv (v2.4.0)- Installing vlucas/phpdotenv (v2.2.0)Downloading: 100%- Removing fzaninotto/faker (v1.6.0)- Installing fzaninotto/faker (v1.5.0)Downloading: 100%- Removing mockery/mockery (0.9.7)- Installing mockery/mockery (0.9.4)Downloading: 100%- Removing phpdocumentor/reflection-docblock (3.1.1)- Installing phpdocumentor/reflection-docblock (2.0.4)Downloading: 100%- Removing phpunit/php-token-stream (1.4.9)- Installing phpunit/php-token-stream (1.4.8)Loading from cache- Removing symfony/yaml (v3.2.1)- Installing symfony/yaml (v3.0.3)Downloading: 100%- Removing sebastian/version (2.0.1)- Installing sebastian/version (1.0.6)Loading from cache- Removing sebastian/recursion-context (2.0.0)- Installing sebastian/recursion-context (1.0.2)Loading from cache- Removing sebastian/exporter (2.0.0)- Installing sebastian/exporter (1.2.1)Downloading: 100%- Removing sebastian/environment (2.0.0)- Installing sebastian/environment (1.3.5)Downloading: 100%- Removing sebastian/comparator (1.2.2)- Installing sebastian/comparator (1.2.0)Loading from cache- Removing phpunit/phpunit-mock-objects (3.4.3)- Installing phpunit/phpunit-mock-objects (2.3.8)Loading from cache- Removing phpunit/php-timer (1.0.8)- Installing phpunit/php-timer (1.0.7)Downloading: 100%- Removing phpunit/php-file-iterator (1.4.2)- Installing phpunit/php-file-iterator (1.4.1)Loading from cache- Removing phpunit/php-code-coverage (4.0.4)- Installing phpunit/php-code-coverage (2.2.4)Loading from cache- Removing phpspec/prophecy (v1.6.2)- Installing phpspec/prophecy (v1.6.0)Downloading: 100%- Removing phpunit/phpunit (5.7.4)- Installing phpunit/phpunit (4.8.24)Downloading: 100%- Removing symfony/css-selector (v3.1.8)- Installing symfony/css-selector (v3.0.3)Downloading: 100%- Removing symfony/dom-crawler (v3.1.8)- Installing symfony/dom-crawler (v3.0.3)Downloading: 100%- Installing psr/http-message (1.0.1)Downloading: 100%- Installing guzzlehttp/psr7 (1.3.1)Downloading: 100%- Installing intervention/image (2.3.7)Downloading: 100%- Removing laravel/framework (v5.3.28)- Installing laravel/framework (v5.2.23)Downloading: 100%- Installing laravelcollective/html (v5.2.4)Downloading: 100%- Installing ezyang/htmlpurifier (v4.8.0)Downloading: 100%- Installing mews/purifier (2.0.6)Downloading: 100%- Installing doctrine/lexer (v1.0.1)Loading from cache- Installing doctrine/annotations (v1.2.7)Loading from cache- Installing doctrine/cache (v1.6.0)Loading from cache- Installing doctrine/collections (v1.3.0)Loading from cache- Installing doctrine/common (v2.6.1)Loading from cache- Installing doctrine/dbal (v2.5.4)Loading from cacheintervention/image suggests installing intervention/imagecache (Caching extension for the Intervention Image library)mews/purifier suggests installing laravel/lumen-framework (To test the Lumen bindings)Generating autoload files> php artisan clear-compiled> php artisan optimizeGenerating optimized class loader
- edit .env file and fill the database account (DB name is laravel_blog)
- Create authentication scaffolding (login, register, forgot password, etc)
123456789101112teddy@teddy-K43SJ:~/Documents/works/laravel/laravel-blog-tutorial$ php artisan make:authCreated View: /home/teddy/Documents/works/laravel/laravel-blog-tutorial/resources/views/auth/login.blade.phpCreated View: /home/teddy/Documents/works/laravel/laravel-blog-tutorial/resources/views/auth/register.blade.phpCreated View: /home/teddy/Documents/works/laravel/laravel-blog-tutorial/resources/views/auth/passwords/email.blade.phpCreated View: /home/teddy/Documents/works/laravel/laravel-blog-tutorial/resources/views/auth/passwords/reset.blade.phpCreated View: /home/teddy/Documents/works/laravel/laravel-blog-tutorial/resources/views/auth/emails/password.blade.phpCreated View: /home/teddy/Documents/works/laravel/laravel-blog-tutorial/resources/views/layouts/app.blade.phpCreated View: /home/teddy/Documents/works/laravel/laravel-blog-tutorial/resources/views/home.blade.phpCreated View: /home/teddy/Documents/works/laravel/laravel-blog-tutorial/resources/views/welcome.blade.phpInstalled HomeController.Updated Routes File.Authentication scaffolding generated successfully! - Use ‘migration’ to add some new tables into the new database
123456789101112teddy@teddy-K43SJ:~/Documents/works/laravel/laravel-blog-tutorial$ php artisan migrateMigration table created successfully.Migrated: 2014_10_12_000000_create_users_tableMigrated: 2014_10_12_100000_create_password_resets_tableMigrated: 2016_02_06_175142_create_posts_tableMigrated: 2016_03_20_162017_add_slug_to_usersMigrated: 2016_04_28_021908_create_categories_tableMigrated: 2016_04_28_022255_add_category_id_to_postsMigrated: 2016_05_30_153615_create_tags_tableMigrated: 2016_05_30_155417_create_post_tag_tableMigrated: 2016_07_16_173641_create_comments_tableMigrated: 2016_08_15_000718_add_image_col_to_posts
It should be ready to test the website. - Dont forget to set the file permission in /public/ directory if we want to upload an image into it
1teddy@teddy-K43SJ:~/Documents/works/laravel/laravel-blog-tutorial$ sudo chmod -R 777 public/ - Test the website: http://localhost:8000/
12teddy@teddy-K43SJ:~/Documents/works/laravel/laravel-blog-tutorial$ php artisan serveLaravel development server started on http://localhost:8000/
If i found an error like:
12RuntimeException in EncryptionServiceProvider.php line 31:No supported encrypter found. The cipher and / or key length are invalid.
Just stop the server then generate the new key:
1teddy@teddy-K43SJ:~/Documents/works/laravel/laravel-blog-tutorial$ php artisan key:generate
It’d create a new key in .env like
1APP_KEY=SRicGuQPSaDDLOlnYCNvz7F2zdYIhXHQ
ref: http://laravel.io/forum/08-25-2016-no-supported-encrypter-found-the-cipher-and-or-key-length-are-invalid-when-i-run-keygenerate.
Then start the server back. If everything is okay, here is the screen look like:
Sometimes you got an error about the file permission writeable or not like this
12NotWritableException in Image.php line 143:Can't write image data to path (/home/teddy/Documents/works/laravel/laravel-blog-tutorial/public/images/1482895274.jpg)
Then you need to set the file permission in /public/ directory to 777
1teddy@teddy-K43SJ:~/Documents/works/laravel/laravel-blog-tutorial$ sudo chmod -R 777 public/
Explore the Laravel Blog!!! (Add/edit users, add/edit posts, categories, tags, comments, send contact, login, register)
If you have enough time to learn the nitty-gritty about laravel and how to create this blog step by step, then please watch this 47 youtube videos in How to Build a Blog with Laravel. - NOTES about this app:
The route file DONT lay in /routes/web.app BUT in /app/Http/routes.php. It used Route::group.
1234567891011121314151617181920212223242526272829303132333435363738394041Route::group(['middleware' => ['web']], function () {// Authentication RoutesRoute::get('auth/login', ['as' => 'login', 'uses' => 'Auth\AuthController@getLogin']);Route::post('auth/login', 'Auth\AuthController@postLogin');Route::get('auth/logout', ['as' => 'logout', 'uses' => 'Auth\AuthController@getLogout']);// Registration RoutesRoute::get('auth/register', 'Auth\AuthController@getRegister');Route::post('auth/register', 'Auth\AuthController@postRegister');// Password Reset RoutesRoute::get('password/reset/{token?}', 'Auth\PasswordController@showResetForm');Route::post('password/email', 'Auth\PasswordController@sendResetLinkEmail');Route::post('password/reset', 'Auth\PasswordController@reset');// CategoriesRoute::resource('categories', 'CategoryController', ['except' => ['create']]);Route::resource('tags', 'TagController', ['except' => ['create']]);// CommentsRoute::post('comments/{post_id}', ['uses' => 'CommentsController@store', 'as' => 'comments.store']);Route::get('comments/{id}/edit', ['uses' => 'CommentsController@edit', 'as' => 'comments.edit']);Route::put('comments/{id}', ['uses' => 'CommentsController@update', 'as' => 'comments.update']);Route::delete('comments/{id}', ['uses' => 'CommentsController@destroy', 'as' => 'comments.destroy']);Route::get('comments/{id}/delete', ['uses' => 'CommentsController@delete', 'as' => 'comments.delete']);Route::get('blog/{slug}', ['as' => 'blog.single', 'uses' => 'BlogController@getSingle'])->where('slug', '[\w\d\-\_]+');Route::get('blog', ['uses' => 'BlogController@getIndex', 'as' => 'blog.index']);Route::get('contact', 'PagesController@getContact');Route::post('contact', 'PagesController@postContact');Route::get('about', 'PagesController@getAbout');Route::get('/', 'PagesController@getIndex');Route::resource('posts', 'PostController');});Route::group(['middleware' => 'web'], function () {Route::auth();Route::get('/home', 'HomeController@index');});
The route for the root website (/) is pointing to ‘PagesController.php’ in /app/Http/Controllers/
1234public function getIndex() {$posts = Post::orderBy('created_at', 'desc')->limit(4)->get();return view('pages.welcome')->withPosts($posts);}
The ‘Post’ data is retrieved with a help from ‘Post’ model in /app/Post.php. The data then would be rendered by welcome.blade.php in /resources/views/pages/
Category: Laravel
Laravel Socialite
Source: https://github.com/laravel/socialite
I want to practice ‘socialite’ app given by Laravel 5.3 documentation. Installation:
- Open hosts file and Add a new domain ‘socialite.app’ at the file
1teddy@teddy-K43SJ:~/Homestead$ sudo gedit /etc/hosts
Add this line in the file:
1192.168.10.10 socialite.app - Edit ‘Homestead.yaml’ file in ~/.homestead/ to add the new domain ‘socialite.app’ and set the mapping
123456...sites:...- map: socialite.appto: /home/vagrant/Code/socialite/public... - Start vagrant with ‘vagrant up’ or if it already started up, refresh it with ‘vagrant provision’ then go into the ssh with ‘vagrant ssh’
- Go into ‘Code’ directory then create a new laravel project ‘socialite’
12345678vagrant@homestead:~$ cd Code/vagrant@homestead:~/Code$ composer create-project --prefer-dist laravel/laravel socialiteInstalling laravel/laravel (v5.3.16)- Installing laravel/laravel (v5.3.16)Loading from cache...> php artisan key:generateApplication key [base64:KYHaOwFIHGLog5xgPO5v1qjP/MDMKO9OL6ajTQGdQ4Q=] set successfully. - Test it at our browser with http://socialite.app/. If the laravel screen is showed up, we are on the right path.
- Go into the new project ‘socialite’ root directory then add a dependency ‘laravel/socialite’
123456789101112131415161718192021222324252627282930vagrant@homestead:~/Code$ cd socialite/vagrant@homestead:~/Code/socialite$ composer require laravel/socialiteUsing version ^2.0 for laravel/socialite./composer.json has been updatedLoading composer repositories with package informationUpdating dependencies (including require-dev)- Installing guzzlehttp/promises (1.3.0)Loading from cache- Installing psr/http-message (1.0.1)Loading from cache- Installing guzzlehttp/psr7 (1.3.1)Loading from cache- Installing guzzlehttp/guzzle (6.2.2)Loading from cache- Installing league/oauth1-client (1.7.0)Downloading: 100%- Installing laravel/socialite (v2.0.20)Downloading: 100%Writing lock fileGenerating autoload files> Illuminate\Foundation\ComposerScripts::postUpdate> php artisan optimizeGenerating optimized class loaderThe compiled class file has been removed.
- Configuration
After installing the Socialite library, register the Laravel\Socialite\SocialiteServiceProvider in your config/app.php configuration file:
12345678...'providers' => [...Laravel\Socialite\SocialiteServiceProvider::class,],...
Also, add the Socialite facade to the aliases array in your app configuration file:
12345678...'aliases' => [...'Socialite' => Laravel\Socialite\Facades\Socialite::class,],...
- You will also need to add credentials for the OAuth services your application utilizes. These credentials should be placed in your config/services.php configuration file, and should use the key facebook, twitter, linkedin, google, github or bitbucket, depending on the providers your application requires. For example for facebook credentials:
12345678910111213<?phpreturn [...'facebook' => ['client_id' => env('FB_APP_ID'),'client_secret' => env('FB_APP_SECRET'),'redirect' => env('FB_REDIRECT'),],];
we will use env file (.env) to store facebook credentials.
123FB_APP_ID=xxxxxxxFB_APP_SECRET=xxxxxxFB_REDIRECT=http://socialite.app/auth/facebook/callback
REMEMBER ‘http://socialite.app/auth/facebook/callback’ IS CALLBACK URL (AFTER THE SUCCESSFUL LOGIN ON FACEBOOK). ALSO IT MUST MATCH WITH ROUTE ‘auth/facebook/callback’ IN /routes/web.php LATER! - Basic Usage
Next, you are ready to authenticate users! You will need two routes: one for redirecting the user to the OAuth provider, and another for receiving the callback from the provider after authentication. We will access Socialite using the Socialite facade. Please create a new controller file ‘AuthController.php’ in /app/Http/Controllers/Auth/ to work with facebook login:
1234567891011121314151617181920212223242526272829303132333435363738<?phpnamespace App\Http\Controllers\Auth;use App\Http\Controllers\Controller;use Socialite;class AuthController extends Controller{/*** Redirect the user to the GitHub authentication page.** @return Response*/public function redirectToProvider(){return Socialite::driver('facebook')->redirect();}/*** Obtain the user information from GitHub.** @return Response*/public function handleProviderCallback(){$user = Socialite::driver('facebook')->user();//var_dump($user);// $user->token;$data=array('name'=>$user->name,'login_via'=>'Facebook');return view('home')->with('data',$data);//return redirect()->to('/')->with('data',$data);}}
NOTE: DONT FORGET TO ADD ‘use App\Http\Controllers\Controller;’ BEFORE ‘use Socialite;’ BECAUSE I GOT AN ERROR ABOUT IT! - Creating Views. Create two new blade files. They are /resources/views/home.blade.php and /resources/views/master.blade.php:
master.blade.php:
123456789101112131415161718192021<!doctype html><html lang="en"><head><meta charset="UTF-8"><meta name="_token" content="{{ csrf_token() }}"/><title>Social Login</title><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"><style>body {padding-top : 70px;}</style></head><body><div class="container">@yield('content')</div><script src="http://code.jquery.com/jquery-2.1.4.min.js"></script></body></html>
home.blade.php:
1234567891011121314@extends('master')@section('content')@if(!empty($data))<h1>Hello {{$data['name']}}, You logged in via {{ $data['login_via'] }}</h1>@else<div class="row"><div class="col-md-6 col-md-offset-3"><h2>Login Using Social Sites</h2><a class="btn btn-primary" href="{{ url('/auth/facebook') }}">Facebook</a></div></div>@endif@stop
url(‘/auth/facebook’) would redirect the page to facebookpage! - Set the routes. Edit /routes/web.php like this:
1234567Route::get('/', function () {//return view('welcome');return view('home');});Route::get('auth/facebook', 'Auth\AuthController@redirectToProvider');Route::get('auth/facebook/callback', 'Auth\AuthController@handleProviderCallback');
We set the root (‘/’) url would open the home page (home.blade.php) - Test it! http://socialite.app/
Here is the screen
If we click ‘Facebook’ link, it would redirect us to facebook page. The url would be like this: https://www.facebook.com/v2.8/dialog/oauth?client_id=166568033366882&redirect_uri=http%3A%2F%2Fsocialite.app&scope=email&response_type=code&state=es6ub834Woh7xDxTvdqru84U7kwiRJkftD83HFz7
If I get this page
Then I need to modify my facebook app to add this domain (http://socialite.app/) at ‘Site URL’ box. To do it, Open your app from https://developers.facebook.com/apps, then Click your app. Then at Settings->Basic->at Site Url fill with this domain name: http://socialite.app/. Then Save and fix any error.
Here is the oauth2 output from facebook for successful login:
Here is the callback result the successful facebook login
- How to add the others social links (twitter, github, google plus and linkedin)?
Please read Complete Laravel 5 Socialite tutorial to find out how to do it.
You need to setup your apps for the above social app to get the credentials like Client ID and Client Secret and the redirect URL.
To setup Google+ app, please read Google APIs
To setup twitter app, please read Twitter Socialite App
To setup github app, please read Github App
To setup linkedin app, please read Linkedin Oauth2 App
Then modify .env file to include above credentials:
- Here I want to make the redirect URL to be uniform like this:
12345678910111213141516171819FB_APP_ID=XXXFB_APP_SECRET=XXXFB_REDIRECT=http://socialite.app/social/login/facebookGOOGLE_APP_ID=XXXGOOGLE_APP_SECRET=XXXGOOGLE_REDIRECT=http://socialite.app/social/login/googleTWITTER_APP_ID=XXXTWITTER_APP_SECRET=XXXTWITTER_REDIRECT=http://socialite.app/social/login/twitterGITHUB_APP_ID=XXXGITHUB_APP_SECRET=XXXGITHUB_REDIRECT=http://socialite.app/social/login/githubLINKEDIN_APP_ID=XXXLINKEDIN_APP_SECRET=XXXLINKEDIN_REDIRECT=http://socialite.app/social/login/linkedin
So modify our social routes in /routes/web.app like this:
12Route::get('social/login/redirect/{provider}', ['uses' => 'Auth\AuthController@redirectToProvider', 'as' => 'social.login']);Route::get('social/login/{provider}', 'Auth\AuthController@handleProviderCallback');
- Modify /config/services.php to get all the credentials from .env file
12345678910111213141516171819202122232425262728293031323334353637<?phpreturn [...'facebook' => ['client_id' => env('FB_APP_ID'),'client_secret' => env('FB_APP_SECRET'),'redirect' => env('FB_REDIRECT'),],'twitter' => ['client_id' => env('TWITTER_APP_ID'),'client_secret' => env('TWITTER_APP_SECRET'),'redirect' => env('TWITTER_REDIRECT'),],'google' => ['client_id' => env('GOOGLE_APP_ID'),'client_secret' => env('GOOGLE_APP_SECRET'),'redirect' => env('GOOGLE_REDIRECT'),],'github' => ['client_id' => env('GITHUB_APP_ID'),'client_secret' => env('GITHUB_APP_SECRET'),'redirect' => env('GITHUB_REDIRECT'),],'linkedin' => ['client_id' => env('LINKEDIN_APP_ID'),'client_secret' => env('LINKEDIN_APP_SECRET'),'redirect' => env('LINKEDIN_REDIRECT'),],];
- Modify /resources/views/home.blade.php to include all the social app
123456789101112131415161718@extends('master')@section('content')@if(!empty($data))<h1>Hello {{$data['name']}}, You logged in via {{ $data['login_via'] }}</h1>@else<div class="row"><div class="col-md-6 col-md-offset-3"><h2>Login Using Social Sites</h2><a class="btn btn-primary" href="{{ route('social.login','facebook') }}">Facebook</a><a class="btn btn-primary" href="{{ route('social.login','twitter') }}">Twitter</a><a class="btn btn-primary" href="{{ route('social.login','google') }}">Google+</a><a class="btn btn-primary" href="{{ route('social.login','github') }}">Github</a><a class="btn btn-primary" href="{{ route('social.login','linkedin') }}">Linkedin</a></div></div>@endif@stop - Modify /app/Http/Controllers/Auth/AuthController.php to add a parameter $provider
1234567891011121314151617181920...class AuthController extends Controller{public function redirectToProvider($provider){return Socialite::driver($provider)->redirect();}public function handleProviderCallback($provider){$user = Socialite::driver($provider)->user();$data=array('name'=>$user->name,'login_via'=>$provider);return view('home')->with('data',$data);}} - Run on your browser
Login via Facebook RUN WELL LIKE BEFORE!
Login via Twitter, For the first time we are needed to authorize the application
Click ‘Authorize app’. If nothing wrong, here is the callback result
Login via Google, For the first time we are needed to authorize the application
Click ‘Izinkan’. If nothing wrong, here is the callback result
Login via Github, For the first time we are needed to authorize the application
Click ‘Authorize application’. If nothing wrong, here is the callback result
Login via Linkedin, For the first time we are needed to authorize the application
Click ‘Allow’. If nothing wrong, here is the callback result
- OKAY! EVERYTHING RUN WELL. THE NEXT STEP IS TO USE DATABASE/SESSION TO SAVE THE LOGIN INFORMATION!
For this, please read : Laravel 5.2 Socialite Facebook Login and Using Github authentication for login with Laravel Socialite.
Laravel Homestead VirtualBox Vagrant
Url: https://laravel.com/docs/5.3/homestead
Quick Tip: Get a Homestead Vagrant VM Up and Running
Getting Started with Laravel Homestead
Introduction
Laravel strives to make the entire PHP development experience delightful, including your local development environment. Vagrant provides a simple, elegant way to manage and provision Virtual Machines.
Laravel Homestead is an official, pre-packaged Vagrant box that provides you a wonderful development environment without requiring you to install PHP, a web server, and any other server software on your local machine. No more worrying about messing up your operating system! Vagrant boxes are completely disposable. If something goes wrong, you can destroy and re-create the box in minutes!
Homestead runs on any Windows, Mac, or Linux system, and includes the Nginx web server, PHP 7.0, MySQL, Postgres, Redis, Memcached, Node, and all of the other goodies you need to develop amazing Laravel applications.
Installation:
- Install VirtualBox (https://www.virtualbox.org/wiki/Linux_Downloads)
- Install Vagrant (https://www.vagrantup.com/downloads.html)
- Installing The Homestead Vagrant Box
1234567891011121314teddy@teddy-K43SJ:~$ vagrant box add laravel/homestead==> box: Loading metadata for box 'laravel/homestead'box: URL: https://atlas.hashicorp.com/laravel/homesteadThis box can work with multiple providers! The providers that itcan work with are listed below. Please review the list and choosethe provider you will be working with.1) virtualbox2) vmware_desktopEnter your choice: 1==> box: Adding box 'laravel/homestead' (v0.6.0) for provider: virtualboxbox: Downloading: https://atlas.hashicorp.com/laravel/boxes/homestead/versions/0.6.0/providers/virtualbox.box==> box: Successfully added box 'laravel/homestead' (v0.6.0) for 'virtualbox'!
- Installing Homestead
12345678teddy@teddy-K43SJ:~$ cd ~teddy@teddy-K43SJ:~$ git clone https://github.com/laravel/homestead.git HomesteadCloning into 'Homestead'...remote: Counting objects: 1675, done.remote: Total 1675 (delta 0), reused 0 (delta 0), pack-reused 1675Receiving objects: 100% (1675/1675), 261.38 KiB | 152.00 KiB/s, done.Resolving deltas: 100% (989/989), done.Checking connectivity... done.
Please check ‘Homestead’ directory at Home (/home/teddy) - Once you have cloned the Homestead repository, run the bash init.sh command from the Homestead directory to create the Homestead.yaml configuration file. The Homestead.yaml file will be placed in the ~/.homestead hidden directory:
123teddy@teddy-K43SJ:~$ cd Homestead/teddy@teddy-K43SJ:~/Homestead$ bash init.shHomestead initialized!
123teddy@teddy-K43SJ:~/Homestead$ cd ~/.homestead/teddy@teddy-K43SJ:~/.homestead$ lsafter.sh aliases Homestead.yaml
- Configuring Homestead. Setting Your Provider
The provider key in your ~/.homestead/Homestead.yaml file indicates which Vagrant provider should be used: virtualbox, vmware_fusion, or vmware_workstation. You may set this to the provider you prefer:
1teddy@teddy-K43SJ:~/.homestead$ gedit Homestead.yaml
Here is the file content looks like:
12345678910111213141516171819202122232425262728293031323334---ip: "192.168.10.10"memory: 2048cpus: 1provider: virtualboxauthorize: ~/.ssh/id_rsa.pubkeys:- ~/.ssh/id_rsafolders:- map: ~/Codeto: /home/vagrant/Codesites:- map: homestead.appto: /home/vagrant/Code/Laravel/publicdatabases:- homestead# blackfire:# - id: foo# token: bar# client-id: foo# client-token: bar# ports:# - send: 50000# to: 5000# - send: 7777# to: 777# protocol: udp
- Configuring Shared Folders
I prefer to let it as is (please see ‘folders’ in ~.homestead/Homestead.yaml file above)–> DON’T DO THIS, IF ‘map’ VALUE STILL ‘~/Code’, PLEASE MODIFY IT (CHECK YOUR WEB DIRECTORY IS BETTER) BECAUSE I GOT THIS ERROR:
1234567teddy@teddy-K43SJ:~/Homestead$ vagrant upBringing machine 'homestead-7' up with 'virtualbox' provider...There are errors in the configuration of this machine. Please fixthe following errors and try again:vm:* The host path of the shared folder is missing: ~/Code
MODIFY IT TO ‘~/Documents/works/laravel’ LIKE THIS:
12345...folders:- map: ~/Documents/works/laravelto: /home/vagrant/Code... - Configuring Nginx Sites
I prefer to let it as is (please see ‘sites’ in ~.homestead/Homestead.yaml file above)
If you change the sites property after provisioning the Homestead box, you should re-run vagrant reload –provision to update the Nginx configuration on the virtual machine. - Configure SSH Key (IF NOT EXIST IN /home/teddy/.ssh/)
1teddy@teddy-K43SJ:~/Homestead$ ssh-keygen -t rsa -C "advcha@yahoo.com" - The Hosts File
You must add the “domains” for your Nginx sites to the hosts file on your machine. The hosts file will redirect requests for your Homestead sites into your Homestead machine. On Mac and Linux, this file is located at /etc/hosts.
1teddy@teddy-K43SJ:~/.homestead$ sudo gedit /etc/hosts
Add this line in the file:
1192.168.10.10 homestead.app
Make sure the IP address listed is the one set in your ~/.homestead/Homestead.yaml file. Once you have added the domain to your hosts file and launched the Vagrant box you will be able to access the site via your web browser: - Launching The Vagrant Box
Once you have edited the Homestead.yaml to your liking, run the vagrant up command from your Homestead directory. Vagrant will boot the virtual machine and automatically configure your shared folders and Nginx sites.
123teddy@teddy-K43SJ:~/.homestead$ cd ~teddy@teddy-K43SJ:~$ cd Homestead/teddy@teddy-K43SJ:~/Homestead$ vagrant up
BUT I GOT THIS ERROR:
123456789101112131415161718192021222324252627/home/teddy/Homestead/scripts/homestead.rb:109:in `read': No such file or directory @ rb_sysopen - /home/teddy/.ssh/id_rsa (Errno::ENOENT)from /home/teddy/Homestead/scripts/homestead.rb:109:in `block (2 levels) in configure'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/plugins/kernel_v2/config/vm_provisioner.rb:72:in `call'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/plugins/kernel_v2/config/vm_provisioner.rb:72:in `add_config'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/plugins/kernel_v2/config/vm.rb:324:in `provision'from /home/teddy/Homestead/scripts/homestead.rb:106:in `block in configure'from /home/teddy/Homestead/scripts/homestead.rb:105:in `each'from /home/teddy/Homestead/scripts/homestead.rb:105:in `configure'from /home/teddy/Homestead/Vagrantfile:30:in `block in <top (required)>'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/lib/vagrant/config/v2/loader.rb:37:in `call'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/lib/vagrant/config/v2/loader.rb:37:in `load'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/lib/vagrant/config/loader.rb:113:in `block (2 levels) in load'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/lib/vagrant/config/loader.rb:107:in `each'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/lib/vagrant/config/loader.rb:107:in `block in load'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/lib/vagrant/config/loader.rb:104:in `each'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/lib/vagrant/config/loader.rb:104:in `load'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/lib/vagrant/vagrantfile.rb:28:in `initialize'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/lib/vagrant/environment.rb:746:in `new'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/lib/vagrant/environment.rb:746:in `vagrantfile'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/lib/vagrant/environment.rb:492:in `host'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/lib/vagrant/environment.rb:214:in `block in action_runner'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/lib/vagrant/action/runner.rb:33:in `call'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/lib/vagrant/action/runner.rb:33:in `run'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/lib/vagrant/environment.rb:479:in `hook'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/lib/vagrant/environment.rb:728:in `unload'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/bin/vagrant:192:in `ensure in <main>'from /opt/vagrant/embedded/gems/gems/vagrant-1.8.7/bin/vagrant:192:in `<main>'
SOLUTION: (ref: Problem launching vagrant on Homestead)
From this error
1No such file or directory @ rb_sysopen - /home/teddy/.ssh/id_rsa (Errno::ENOENT)
I didn’t find ‘id_rsa’ file in /home/teddy/.ssh/ directory. I need to configure my SSH location like this:
123456789101112131415161718192021teddy@teddy-K43SJ:~/Homestead$ ssh-keygen -t rsa -C "advcha@yahoo.com"Generating public/private rsa key pair.Enter file in which to save the key (/home/teddy/.ssh/id_rsa):Enter passphrase (empty for no passphrase):Enter same passphrase again:Your identification has been saved in /home/teddy/.ssh/id_rsa.Your public key has been saved in /home/teddy/.ssh/id_rsa.pub.The key fingerprint is:b6:7b:c7:0c:c9:d1:3d:a7:8b:8f:56:25:52:2b:6a:48 advcha@yahoo.comThe key's randomart image is:+--[ RSA 2048]----+| || . || . o . || E . + = o|| .So + o * || ...* o || .. + o . || .. *.. || .. o... |+-----------------+
SEE MY MODIFICATION AT #9.
Then I run ‘vagrant up’ again. BUT GOT ANOTHER ERROR:
1234567teddy@teddy-K43SJ:~/Homestead$ vagrant upBringing machine 'homestead-7' up with 'virtualbox' provider...There are errors in the configuration of this machine. Please fixthe following errors and try again:vm:* The host path of the shared folder is missing: ~/Code
SOLUTION: (ref: Vagrant: The host path of the shared folder is missing)
SEE MY MODIFICATION AT #7 ABOVE!
RUN ‘vagrant up’ again! SUCCESS:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960teddy@teddy-K43SJ:~/Homestead$ vagrant upBringing machine 'homestead-7' up with 'virtualbox' provider...==> homestead-7: Importing base box 'laravel/homestead'...==> homestead-7: Matching MAC address for NAT networking...==> homestead-7: Checking if box 'laravel/homestead' is up to date...==> homestead-7: Setting the name of the VM: homestead-7==> homestead-7: Clearing any previously set network interfaces...==> homestead-7: Preparing network interfaces based on configuration...homestead-7: Adapter 1: nathomestead-7: Adapter 2: hostonly==> homestead-7: Forwarding ports...homestead-7: 80 (guest) => 8000 (host) (adapter 1)homestead-7: 443 (guest) => 44300 (host) (adapter 1)homestead-7: 3306 (guest) => 33060 (host) (adapter 1)homestead-7: 5432 (guest) => 54320 (host) (adapter 1)homestead-7: 22 (guest) => 2222 (host) (adapter 1)==> homestead-7: Running 'pre-boot' VM customizations...==> homestead-7: Booting VM...==> homestead-7: Waiting for machine to boot. This may take a few minutes...homestead-7: SSH address: 127.0.0.1:2222homestead-7: SSH username: vagranthomestead-7: SSH auth method: private keyhomestead-7:homestead-7: Vagrant insecure key detected. Vagrant will automatically replacehomestead-7: this with a newly generated keypair for better security.homestead-7:homestead-7: Inserting generated public key within guest...homestead-7: Removing insecure key from the guest if it's present...homestead-7: Key inserted! Disconnecting and reconnecting using new SSH key...==> homestead-7: Machine booted and ready!==> homestead-7: Checking for guest additions in VM...==> homestead-7: Setting hostname...==> homestead-7: Configuring and enabling network interfaces...==> homestead-7: Mounting shared folders...homestead-7: /vagrant => /home/teddy/Homesteadhomestead-7: /home/vagrant/Code => /home/teddy/Documents/works/laravel==> homestead-7: Running provisioner: file...==> homestead-7: Running provisioner: shell...homestead-7: Running: inline script==> homestead-7:==> homestead-7: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDFs0+Hb8l+48Eq9Ac6kXclhIuecnLDF6W5jocqSQBcLjdixzCnwnvciW26PvUp2HEjzkzAX8s56Zx4v4cBJUoRRx7yxU60y3HeFDOFzrZEicnI/10iwnmedFcm6SdvhhQvenVev8neZjI4SCnjAKvoTgu/RKkHiU9wBVXhb7gHl0qkvo5333I9l8bMqjWQqdD7GDTjfdrbddQD0QrxR+aU+Hbpo6E1w7htbQ0iic/Nif4oXjRQrQpgwHKA591oGyfAlqDNrQ361SZehIO0ZIBv/3+am5696AluSTkm5DZW1TdidMChFKVIah9VcSZ3K+yRvtpavpCsJwfrnFLsjq+9 advcha@yahoo.com==> homestead-7: Running provisioner: shell...homestead-7: Running: inline script==> homestead-7: Running provisioner: shell...homestead-7: Running: /tmp/vagrant-shell20161122-2322-u1zhuj.sh==> homestead-7: Running provisioner: shell...homestead-7: Running: script: Creating Site: homestead.app==> homestead-7: Running provisioner: shell...homestead-7: Running: script: Restarting Nginx==> homestead-7: Running provisioner: shell...homestead-7: Running: script: Creating MySQL Database==> homestead-7: Running provisioner: shell...homestead-7: Running: script: Creating Postgres Database==> homestead-7: Running provisioner: shell...homestead-7: Running: script: Clear Variables==> homestead-7: Running provisioner: shell...homestead-7: Running: script: Update Composer==> homestead-7: You are already using composer version 1.2.2 (stable channel).==> homestead-7: Running provisioner: shell...homestead-7: Running: /tmp/vagrant-shell20161122-2322-tjn045.sh
WE CAN SEE VAGRANT INSTALLED ALSO PHP, NGINX, MYSQL, POSTGRESQL,ETC.
Or you can see it from VirtualBox (Open Applications -> System Tools -> Oracle VM VirtualBox)
THIS GUI MORE CONVENIENT. I CAN ‘START’, ‘PAUSE’ OR ‘CLOSE->POWER OFF’ THE VIRTUAL MACHINE!
NOTE: START MUST BE FROM TERMINAL BY TYPING ‘vagrant up’. I CAN USE GUI TO START IT UP BECAUSE IT’S ALWAYS ASK FOR LOGIN AND PASSWORD THAT I DONT KNOW!
USE ‘vagrant provision’ TO RELOAD/REFRESH VM!
TO SHUTDOWN THE VM (NO! USE SUSPEND INSTEAD. SEE BELOW), PLEASE TYPE ‘vagrant destroy –force’
READ (https://www.vagrantup.com/docs/cli/destroy.html): “The destroy command does not remove a box that may have been installed on your computer during vagrant up. Thus, even if you run vagrant destroy, the box installed in the system will still be present on the hard drive. To return your computer to the state as it was before vagrant up command, you need to use vagrant box remove.”
USE SUSPEND INSTEAD OF SHUTDOWN (ref:https://scotch.io/tutorials/getting-started-with-laravel-homestead)
12teddy@teddy-K43SJ:~/Homestead$ vagrant suspend==> homestead-7: Saving VM state and suspending execution...
SOMETIMES I FORGOT TO SUSPEND THE VM BEFORE HIBERNATING MY LAPTOP. IT’D MAKE MY LAPTOP VERY SLOW. THE TERMINAL WOULD NOT RESPOND ANYMORE FOR ANYKEY BUT I CAN OPEN THE NEW ONE OR NEW TAB. USUALLY THE VM STATUS IS PAUSED.
1234567891011teddy@teddy-K43SJ:~/Homestead$ vagrant statusCurrent machine states:homestead-7 paused (virtualbox)The VM is paused. This VM may have been paused via the VirtualBoxGUI or the VBoxManage command line interface. To unpause, pleaseuse the VirtualBox GUI and/or VBoxManage command line interface sothat vagrant would be able to control the VM again.teddy@teddy-K43SJ:~/Homestead$ vagrant provision==> homestead-7: VM is not currently running. Please, first bring it up with `vagrant up` then run this command.
I HAVE TO OPEN THE VirtualBox GUI AND DO Close -> Save State MANUALLY TO STOP THE CURRENT PROCESS!
123456teddy@teddy-K43SJ:~/Homestead$ vagrant statusCurrent machine states:homestead-7 saved (virtualbox)To resume this VM, simply run `vagrant up`.
- Use SSH to get into the VM (ref: https://www.sitepoint.com/quick-tip-get-homestead-vagrant-vm-running/)
123456789101112teddy@teddy-K43SJ:~/Homestead$ vagrant sshWelcome to Ubuntu 16.04.1 LTS (GNU/Linux 4.4.0-38-generic x86_64)* Documentation: https://help.ubuntu.com* Management: https://landscape.canonical.com* Support: https://ubuntu.com/advantage4 packages can be updated.0 updates are security updates.vagrant@homestead:~$
It seems vagrant INSTALLED ubuntu 16.04 AS VM!
I can check the PHP version like this:
123456vagrant@homestead:~$ php -vPHP 7.0.13-1+deb.sury.org~xenial+1 (cli) ( NTS )Copyright (c) 1997-2016 The PHP GroupZend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologieswith Zend OPcache v7.0.13-1+deb.sury.org~xenial+1, Copyright (c) 1999-2016, by Zend Technologieswith blackfire v1.14.1~linux-x64-non_zts70, https://blackfire.io, by Blackfireio Inc.
I can browse the files and directories in it:
123456vagrant@homestead:~$ lsCodevagrant@homestead:~$ cd Code/vagrant@homestead:~/Code$ lsblog composer.lock latihan-crudcomposer.json crud-materialize mylaravelproject - Run http://homestead.app
But before we do this, WE NEED TO ADD A FEW DIRECTORIES AND FILE. BECAUSE WE KNOW THE WEB ROOT FOR OUR VM IS ‘/home/vagrant/Code’ IS MAPPED TO ‘~/Documents/works/laravel’ (SEE ~/.homestead/Homestead.yaml). FOR ‘homestead.app’ (IS MAPPED TO ‘/home/vagrant/Code/Laravel/public’), ADD A NEW DIRECTORY ‘Laravel’ in /Documents/works/laravel/, THEN ADD ‘public’ DIRECTORY IN IT. THEN ADD A NEW FILE ‘index.php’ IN IT. SO THE FULL PATH IS ‘/Documents/works/laravel/Laravel/public/index.php’. In the PHP file, just add a line of code:
123<?phpphpinfo();?>
THEN RUN http://homestead.app/ IN OUR BROWSER!
I can see I’m using NGINX as a webserver instead of Apache

HOW TO RUN MYSQL DATABASE???
SOLUTION:
REMEMBER: VAGRANT MUST BE IN ‘UP’ MODE FOR THIS SITUATION!
Login to ssh (‘vagrant ssh’) then check the mysql location with ‘which mysql’
1234567891011121314teddy@teddy-K43SJ:~/Homestead$ vagrant sshWelcome to Ubuntu 16.04.1 LTS (GNU/Linux 4.4.0-38-generic x86_64)* Documentation: https://help.ubuntu.com* Management: https://landscape.canonical.com* Support: https://ubuntu.com/advantage4 packages can be updated.0 updates are security updates.Last login: Wed Nov 23 07:27:28 2016 from 10.0.2.2vagrant@homestead:~$ which mysql/usr/bin/mysql
From ~/.homestead/Homestead.yaml, here is the databases:
12databases:- homestead
To connect to mysql server at VM, use default user:
12user: homesteadpassword: secret
12345678910111213141516vagrant@homestead:~$ mysql -uhomestead -psecretmysql: [Warning] Using a password on the command line interface can be insecure.Welcome to the MySQL monitor. Commands end with ; or \g.Your MySQL connection id is 11Server version: 5.7.16-0ubuntu0.16.04.1 (Ubuntu)Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.Oracle is a registered trademark of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respectiveowners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql> quitBye
So MYSQL Server version is 5.7.16
For better for myself to connect to the mysql server, I tried to install the latest mysql client ‘MySQL Workbench’ from https://dev.mysql.com/downloads/workbench/.
<OLD>
Currently the version is 6.3.8. But when I installed it, I got dependenci error “Dependency is not satisfiable: libatkmm-1.6-1v5 (>=2.24.0)”. I checked again the downloaded file (mysql-workbench-community-6.3.8-1ubu1604-amd64.deb), IT’S APPARENTLY FOR UBUNTU 16.04!
</OLD>
<NEW>
Ref: http://elementaryos.stackexchange.com/questions/6779/cant-install-mysql-workbench-dependency-is-not-satisfiable
Download MySQL Workbench for Ubuntu 14.04 here http://cdn.mysql.com//archives/mysql-workbench/mysql-workbench-community-6.3.6-1ubu1404-amd64.deb THEN INSTALL. SUCCESS!
</NEW>
CONFIGURE MySQL Worbench TO CONNECT MySQL Server AT VM:
123456Connection Name: vagrantHostname: 192.168.10.10User: homesteadPassword: secretPort: 3306Default Schema: homestead

Now I can see the database ‘homestead’. I also can create any table!
WHERE IS NGINX CONFIGURATION FILE???
SOLUTION:
Use ‘vagrant ssh’ TO GET INTO THE HOME DIRECTORY OF VM. THEN GO TO THE ROOT DIRECTORY
1234567891011121314151617181920212223teddy@teddy-K43SJ:~/Homestead$ vagrant sshWelcome to Ubuntu 16.04.1 LTS (GNU/Linux 4.4.0-38-generic x86_64)* Documentation: https://help.ubuntu.com* Management: https://landscape.canonical.com* Support: https://ubuntu.com/advantage4 packages can be updated.0 updates are security updates.Last login: Wed Nov 23 07:51:16 2016 from 10.0.2.2vagrant@homestead:~$ lsCodevagrant@homestead:~$ cd ..vagrant@homestead:/home$ lsvagrantvagrant@homestead:/home$ cd ..vagrant@homestead:/$ lsbin home lib64 opt sbin tmp vmlinuzboot initrd.img lost+found proc snap usr vmlinuz.olddev initrd.img.old media root srv vagrantetc lib mnt run sys var
THE NGINX CONF FILE IN /etc/nginx/nginx.conf
1234567vagrant@homestead:/$ cd /etc/nginx/vagrant@homestead:/etc/nginx$ lsconf.d koi-win proxy_params sslfastcgi.conf mime.types scgi_params uwsgi_paramsfastcgi_params modules-available sites-available win-utfhhvm.conf modules-enabled sites-enabledkoi-utf nginx.conf snippets
USE ‘nano’ TO OPEN/EDIT THE FILE
1vagrant@homestead:/$ nano /etc/nginx/nginx.conf
Here is the file content:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586user vagrant;worker_processes auto;pid /run/nginx.pid;include /etc/nginx/modules-enabled/*.conf;events {worker_connections 768;# multi_accept on;}http {### Basic Settings##sendfile on;tcp_nopush on;tcp_nodelay on;keepalive_timeout 65;types_hash_max_size 2048;# server_tokens off;server_names_hash_bucket_size 64;# server_name_in_redirect off;include /etc/nginx/mime.types;default_type application/octet-stream;### SSL Settings##ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLEssl_prefer_server_ciphers on;### Logging Settings##access_log /var/log/nginx/access.log;error_log /var/log/nginx/error.log;### Gzip Settings##gzip on;gzip_disable "msie6";# gzip_vary on;# gzip_proxied any;# gzip_comp_level 6;# gzip_buffers 16 8k;# gzip_http_version 1.1;# gzip_types text/plain text/css application/json application/javascrip$### Virtual Host Configs##include /etc/nginx/conf.d/*.conf;include /etc/nginx/sites-enabled/*;}#mail {# # See sample authentication script at:# # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript## # auth_http localhost/auth.php;# # pop3_capabilities "TOP" "USER";# # imap_capabilities "IMAP4rev1" "UIDPLUS";## server {# listen localhost:110;# protocol pop3;# proxy on;# }## server {# listen localhost:143;# protocol imap;# proxy on;# }#}
TIPS FOR USING NANO:
TO ‘COPY’ THE TEXT AT THE TERMINAL, JUST USE MOUSE & DRAG THEN Edit->Copy
TO ‘EXIT’ THE TERMINAL, PRESS ‘Ctrl+X’
use CTRL-O to Save/overwrite the changes then ENTER - HOW TO CREATE NEW PROJECT ON VAGRANT???
OK!. Make sure to run the VM (‘vagrant up’) and go to the ssh (‘vagrant ssh’). I want to clone the laravel 5 project here (Please read Install Laravel 5 On Ubuntu 14.04) For the first time, check our git and composer:
1234vagrant@homestead:~$ git --versiongit version 2.7.4vagrant@homestead:~$ composer --versionComposer version 1.2.2 2016-11-03 17:43:15
GO TO ‘/Code’ DIRECTORY FIRST!
1vagrant@homestead:~$ cd Code/
NOTE: THIS IS A REMAINDER! I MADE A MISTAKE FOR THE FIRST TIME SO I HAVE TO MOVE THE LARAVEL PROJECT INTO ‘/Code’ DIRECTORY!
1vagrant@homestead:~$ mv laravelvagrant/ Code/
OK. Create the Laravel project with name ‘laravelvagrant’
1234567vagrant@homestead:~/Code$ composer create-project --prefer-dist laravel/laravel laravelvagrantInstalling laravel/laravel (v5.3.16)- Installing laravel/laravel (v5.3.16)Downloading: 100%...> php artisan key:generateApplication key [base64:n13iBSiaaoRlpmuP9Mu1B4aL1SUSv2oCMEveVnY8NbQ=] set successfully.
CHECK THE NEW PROJECT ‘laravelvagrant’!
123vagrant@homestead:~/Code$ lsblog composer.lock Laravel latihan-crudcomposer.json crud-materialize laravelvagrant mylaravelproject
We want to run this new project, BUT we need to modify ‘Homestead.yaml’ file first to map ‘homestead.app’ to our new project ‘laravelvagrant’. Here is the modification:
123sites:- map: homestead.appto: /home/vagrant/Code/laravelvagrant/public
We changed from ‘/home/vagrant/Code/Laravel/public’ to ‘/home/vagrant/Code/laravelvagrant/public’
THEN WE NEED TO REFRESH OUR VM WITH ‘vagrant provision’! (exit from ssh first!). Then IT’S READY TO RUN homestead.app (http://homestead.app/) ON OUR BROWSER! HERE IS THE WELCOME SCREEN
- I have a test from interviewed.com (https://upwork.interviewed.com/candidate/interviews/905600) from upwork.com about my understanding for PHP things to go into the enterprise level!. Here is the description:
“This project assumes your computer is already set up with minimal development tools including Git, Vagrant, Composer, etc. If you don’t already have these installed, you may want to switch to the computer that you normally develop on or follow these instructions.This project uses Laravel 5.3, PHP 7.0, and SQLite (so that database is portable without seeds).Download the project and start your server:
https://github.com/prehire/php-23093023909ad09a09
View the project in your browser and click around: http://homestead.appMost people allocate about 1 hour to this project, but you can invest up to 4 hours if you want to. Because the project has a time limit, you can’t pause once you’ve started.”
OK! I already setup vagrant and virtualbox
Run the VM and go into the ssh
Then clone the project ‘https://github.com/prehire/php-23093023909ad09a09.git’
1234567891011vagrant@homestead:~/Code$ git clone https://github.com/prehire/php-23093023909ad09a09.gitCloning into 'php-23093023909ad09a09'...remote: Counting objects: 152, done.remote: Total 152 (delta 0), reused 0 (delta 0), pack-reused 152Receiving objects: 100% (152/152), 174.46 KiB | 191.00 KiB/s, done.Resolving deltas: 100% (30/30), done.Checking connectivity... done.vagrant@homestead:~/Code$ lsblog crud-materialize latihan-crudcomposer.json Laravel mylaravelprojectcomposer.lock laravelvagrant php-23093023909ad09a09
Go into the project ‘php-23093023909ad09a09’ then install the dependencies via composer
123456789101112vagrant@homestead:~/Code$ cd php-23093023909ad09a09/vagrant@homestead:~/Code/php-23093023909ad09a09$ composer installLoading composer repositories with package informationInstalling dependencies (including require-dev) from lock file- Installing nikic/php-parser (v2.1.1)Loading from cache...Generating autoload files> Illuminate\Foundation\ComposerScripts::postInstall> php artisan optimizeGenerating optimized class loaderThe compiled class file has been removed.
Now we want to test it on our browser BUT REMEMBER TO MODIFY ‘Homestead.yaml’ FIRST!
123sites:- map: homestead.appto: /home/vagrant/Code/php-23093023909ad09a09/public
THEN EXIT FROM SSH & REFRESH OUR VM WITH ‘vagrant provision’!
REFRESH OUR BROWSER (http://homestead.app/). HERE IS THE HOMEPAGE SCREEN!
The App with 4 top menu: Homework (http://homestead.app/booking OR http://homestead.app/ –> HOMEPAGE), Booking (http://homestead.app/booking), Customer (http://homestead.app/customer) and Cleaner (http://homestead.app/cleaner). Here are the screens for each of them:
Booking
Customer
Cleaner
OK. THE SETUP IS OKAY. WHAT IS THE TASK FOR THIS PROJECT???
USE PDO INSTEAD OF MYSQL!!! SETUP IT FIRST OR TRY THE AVAILABLE PROJECT IN http://myprojects.advchaweb.com/index.php/2017/01/11/cleaner-booking/ TO MAKE SURE PDO WORK IN HOMESTEAD!
Laravel CRUD With MaterializeCSS
Source: Tutorial CRUD Sederhana Laravel 5.2 dengan Materializecss Part I
& Tutorial CRUD Sederhana Laravel 5.2 dengan Materializecss Part II
MaterializeCSS source: http://materializecss.com/getting-started.html (I don’t use sass, so download the newest version http://materializecss.com/bin/materialize-v0.97.7.zip)
- Create a new laravel project named ‘crud-materialize’
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255teddy@teddy-K43SJ:~/Documents/works/laravel$ composer create-project --prefer-dist laravel/laravel crud-materializeInstalling laravel/laravel (v5.3.16)- Installing laravel/laravel (v5.3.16)Loading from cacheCreated project in crud-materialize> php -r "file_exists('.env') || copy('.env.example', '.env');"Loading composer repositories with package informationUpdating dependencies (including require-dev)- Installing vlucas/phpdotenv (v2.4.0)Loading from cache- Installing symfony/polyfill-mbstring (v1.2.0)Loading from cache- Installing symfony/var-dumper (v3.1.6)Downloading: 100%- Installing symfony/translation (v3.1.6)Downloading: 100%- Installing symfony/routing (v3.1.6)Loading from cache- Installing symfony/process (v3.1.6)Loading from cache- Installing psr/log (1.0.2)Loading from cache- Installing symfony/debug (v3.1.6)Loading from cache- Installing symfony/http-foundation (v3.1.6)Downloading: 100%- Installing symfony/event-dispatcher (v3.1.6)Downloading: 100%- Installing symfony/http-kernel (v3.1.6)Downloading: 100%- Installing symfony/finder (v3.1.6)Loading from cache- Installing symfony/console (v3.1.6)Downloading: 100%- Installing swiftmailer/swiftmailer (v5.4.3)Loading from cache- Installing paragonie/random_compat (v2.0.3)Loading from cache- Installing ramsey/uuid (3.5.1)Loading from cache- Installing jakub-onderka/php-console-color (0.1)Loading from cache- Installing jakub-onderka/php-console-highlighter (v0.3.2)Loading from cache- Installing dnoegel/php-xdg-base-dir (0.1)Loading from cache- Installing nikic/php-parser (v2.1.1)Loading from cache- Installing psy/psysh (v0.7.2)Loading from cache- Installing nesbot/carbon (1.21.0)Loading from cache- Installing mtdowling/cron-expression (v1.1.0)Loading from cache- Installing monolog/monolog (1.21.0)Loading from cache- Installing league/flysystem (1.0.32)Loading from cache- Installing symfony/polyfill-util (v1.2.0)Loading from cache- Installing symfony/polyfill-php56 (v1.2.0)Loading from cache- Installing jeremeamia/superclosure (2.2.0)Loading from cache- Installing doctrine/inflector (v1.1.0)Loading from cache- Installing classpreloader/classpreloader (3.0.0)Loading from cache- Installing laravel/framework (v5.3.21)Downloading: 100%- Installing fzaninotto/faker (v1.6.0)Loading from cache- Installing hamcrest/hamcrest-php (v1.2.2)Loading from cache- Installing mockery/mockery (0.9.5)Loading from cache- Installing symfony/yaml (v3.1.6)Downloading: 100%- Installing sebastian/version (2.0.0)Loading from cache- Installing sebastian/resource-operations (1.0.0)Loading from cache- Installing sebastian/recursion-context (1.0.2)Loading from cache- Installing sebastian/object-enumerator (1.0.0)Loading from cache- Installing sebastian/global-state (1.1.1)Loading from cache- Installing sebastian/exporter (1.2.2)Loading from cache- Installing sebastian/environment (1.3.8)Loading from cache- Installing sebastian/diff (1.4.1)Loading from cache- Installing sebastian/comparator (1.2.0)Loading from cache- Installing doctrine/instantiator (1.0.5)Loading from cache- Installing phpunit/php-text-template (1.2.1)Loading from cache- Installing phpunit/phpunit-mock-objects (3.4.0)Loading from cache- Installing phpunit/php-timer (1.0.8)Loading from cache- Installing phpunit/php-file-iterator (1.4.1)Loading from cache- Installing sebastian/code-unit-reverse-lookup (1.0.0)Loading from cache- Installing phpunit/php-token-stream (1.4.8)Loading from cache- Installing phpunit/php-code-coverage (4.0.1)Loading from cache- Installing webmozart/assert (1.1.0)Loading from cache- Installing phpdocumentor/reflection-common (1.0)Loading from cache- Installing phpdocumentor/type-resolver (0.2)Loading from cache- Installing phpdocumentor/reflection-docblock (3.1.1)Loading from cache- Installing phpspec/prophecy (v1.6.1)Loading from cache- Installing myclabs/deep-copy (1.5.4)Loading from cache- Installing phpunit/phpunit (5.6.2)Downloading: 100%- Installing symfony/css-selector (v3.1.6)Loading from cache- Installing symfony/dom-crawler (v3.1.6)Downloading: 100%symfony/var-dumper suggests installing ext-symfony_debug ()symfony/translation suggests installing symfony/config ()symfony/routing suggests installing doctrine/annotations (For using the annotation loader)symfony/routing suggests installing symfony/config (For using the all-in-one router or any loader)symfony/routing suggests installing symfony/dependency-injection (For loading routes from a service)symfony/routing suggests installing symfony/expression-language (For using expression matching)symfony/event-dispatcher suggests installing symfony/dependency-injection ()symfony/http-kernel suggests installing symfony/browser-kit ()symfony/http-kernel suggests installing symfony/class-loader ()symfony/http-kernel suggests installing symfony/config ()symfony/http-kernel suggests installing symfony/dependency-injection ()paragonie/random_compat suggests installing ext-libsodium (Provides a modern crypto API that can be used to generate random bytes.)ramsey/uuid suggests installing ircmaxell/random-lib (Provides RandomLib for use with the RandomLibAdapter)ramsey/uuid suggests installing ext-libsodium (Provides the PECL libsodium extension for use with the SodiumRandomGenerator)ramsey/uuid suggests installing ext-uuid (Provides the PECL UUID extension for use with the PeclUuidTimeGenerator and PeclUuidRandomGenerator)ramsey/uuid suggests installing moontoast/math (Provides support for converting UUID to 128-bit integer (in string form).)ramsey/uuid suggests installing ramsey/uuid-doctrine (Allows the use of Ramsey\Uuid\Uuid as Doctrine field type.)ramsey/uuid suggests installing ramsey/uuid-console (A console application for generating UUIDs with ramsey/uuid)psy/psysh suggests installing ext-pdo-sqlite (The doc command requires SQLite to work.)monolog/monolog suggests installing aws/aws-sdk-php (Allow sending log messages to AWS services like DynamoDB)monolog/monolog suggests installing doctrine/couchdb (Allow sending log messages to a CouchDB server)monolog/monolog suggests installing ext-amqp (Allow sending log messages to an AMQP server (1.0+ required))monolog/monolog suggests installing ext-mongo (Allow sending log messages to a MongoDB server)monolog/monolog suggests installing graylog2/gelf-php (Allow sending log messages to a GrayLog2 server)monolog/monolog suggests installing mongodb/mongodb (Allow sending log messages to a MongoDB server via PHP Driver)monolog/monolog suggests installing php-amqplib/php-amqplib (Allow sending log messages to an AMQP server using php-amqplib)monolog/monolog suggests installing php-console/php-console (Allow sending log messages to Google Chrome)monolog/monolog suggests installing rollbar/rollbar (Allow sending log messages to Rollbar)monolog/monolog suggests installing ruflin/elastica (Allow sending log messages to an Elastic Search server)monolog/monolog suggests installing sentry/sentry (Allow sending log messages to a Sentry server)league/flysystem suggests installing league/flysystem-aws-s3-v2 (Allows you to use S3 storage with AWS SDK v2)league/flysystem suggests installing league/flysystem-aws-s3-v3 (Allows you to use S3 storage with AWS SDK v3)league/flysystem suggests installing league/flysystem-azure (Allows you to use Windows Azure Blob storage)league/flysystem suggests installing league/flysystem-cached-adapter (Flysystem adapter decorator for metadata caching)league/flysystem suggests installing league/flysystem-copy (Allows you to use Copy.com storage)league/flysystem suggests installing league/flysystem-dropbox (Allows you to use Dropbox storage)league/flysystem suggests installing league/flysystem-eventable-filesystem (Allows you to use EventableFilesystem)league/flysystem suggests installing league/flysystem-rackspace (Allows you to use Rackspace Cloud Files)league/flysystem suggests installing league/flysystem-sftp (Allows you to use SFTP server storage via phpseclib)league/flysystem suggests installing league/flysystem-webdav (Allows you to use WebDAV storage)league/flysystem suggests installing league/flysystem-ziparchive (Allows you to use ZipArchive adapter)laravel/framework suggests installing aws/aws-sdk-php (Required to use the SQS queue driver and SES mail driver (~3.0).)laravel/framework suggests installing doctrine/dbal (Required to rename columns and drop SQLite columns (~2.4).)laravel/framework suggests installing guzzlehttp/guzzle (Required to use the Mailgun and Mandrill mail drivers and the ping methods on schedules (~5.3|~6.0).)laravel/framework suggests installing league/flysystem-aws-s3-v3 (Required to use the Flysystem S3 driver (~1.0).)laravel/framework suggests installing league/flysystem-rackspace (Required to use the Flysystem Rackspace driver (~1.0).)laravel/framework suggests installing pda/pheanstalk (Required to use the beanstalk queue driver (~3.0).)laravel/framework suggests installing predis/predis (Required to use the redis cache and queue drivers (~1.0).)laravel/framework suggests installing pusher/pusher-php-server (Required to use the Pusher broadcast driver (~2.0).)laravel/framework suggests installing symfony/psr-http-message-bridge (Required to use psr7 bridging features (0.2.*).)sebastian/global-state suggests installing ext-uopz (*)phpunit/phpunit-mock-objects suggests installing ext-soap (*)phpunit/php-code-coverage suggests installing ext-xdebug (>=2.4.0)phpunit/phpunit suggests installing phpunit/php-invoker (~1.1)phpunit/phpunit suggests installing ext-xdebug (*)Writing lock fileGenerating autoload files> Illuminate\Foundation\ComposerScripts::postUpdate> php artisan optimizeGenerating optimized class loaderThe compiled class file has been removed.> php artisan key:generateApplication key [base64:bcsSsz8gPXQrB5rmUX4zXCmfkbIt6QW7IFiC/01QpRQ=] set successfully.
- Download materialize from the above link if haven’t downloaded it. Then extract the file. Here is how the folders and files look after extracting
Only 3 folders (css, fonts and js) and 2 files.
Then copy/cut the above folders and file into ‘public’ in our laravel project directory (/crud-materialize/public/). It’ll merge the css and js folders. - Go into the project directory ‘crud-materialize’ then create a controller with name ‘CrudController’
123teddy@teddy-K43SJ:~/Documents/works/laravel$ cd crud-materialize/teddy@teddy-K43SJ:~/Documents/works/laravel/crud-materialize$ php artisan make:controller CrudController --resourceController created successfully.
We can look up the new file CrudController.php in /app/Http/Controllers/ directory. - Modify CrudController.php then edit ‘index’ function to call our view. It’d be like this:
1234public function index(){return view('show');}
- Modify /routes/web.php to change the default route (welcome) to call index function in CrudController:
1234/*Route::get('/', function () {return view('welcome');});*/Route::get('/','CrudController@index'); - It’s time to mess with the views. Create a new directory ‘layouts’ in /resources/views/. Then in it (layouts), create two blades files: index.blade.php and header.blade.php. Also create a new blade file show.blade.php in /resources/views/:
/resources/views/layouts/index.blade.php:
123456789101112131415161718192021222324252627282930313233<!DOCTYPE html><html><head><title>CRUD Laravel With Materializecss</title><link rel="stylesheet" href="{{asset('css/materialize.min.css')}}"><link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"><meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">@section('css')@show</head><body>@section('header')@include('layouts.header')@show<div class="container">@yield('content')</div><script src="https://code.jquery.com/jquery-2.1.1.min.js"></script><script src="{{asset('js/materialize.min.js')}}"></script><script type="text/javascript">(function($){$(function(){$('.button-collapse').sideNav();}); // end of document ready})(jQuery); // end of jQuery name space</script></body></html>
/resources/views/layouts/header.blade.php:
12345678910111213<nav class="pink accent-3" role="navigation"><div class="nav-wrapper container"><a id="logo-container" href="#" class="brand-logo">Laravel</a><ul class="right hide-on-med-and-down"><li><a href="{{ url('/')}}">Home</a></li></ul><ul id="nav-mobile" class="side-nav"><li><a href="{{ url('/')}}">Home</a></li></ul><a href="#" data-activates="nav-mobile" class="button-collapse"><i class="material-icons">menu</i></a></div></nav>
/resources/views/show.blade.php:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657@extends('layouts.index')@section('content')<div class="section"><div class="card-panel purple darken-3 white-text">Tutorial - CRUD Laravel With Materializecss</div></div><div class="section"><div class="row"><div class="col s12"><h5>Here the title</h5><div class="divider"></div><p>Sriracha biodiesel taxidermy organic post-ironic, Intelligentsia salvia mustache 90's code editing brunch. Butcher polaroid VHS art party, hashtag Brooklyn deep v PBR narwhal sustainable mixtape swag wolf squid tote bag. Tote bag cronut semiotics,</p><button class="btn btn-flat pink accent-3 waves-effect waves-light white-text">Readmore <i class="material-icons right">send</i></button><button class="btn btn-flat purple darken-4 waves-effect waves-light white-text">Edit <i class="material-icons right">mode_edit</i></button><button class="btn btn-flat red darken-4 waves-effect waves-light white-text">Delete <i class="material-icons right">delete</i></button></div></div><div class="row"><div class="col s12"><h5>Here the title</h5><div class="divider"></div><p>Sriracha biodiesel taxidermy organic post-ironic, Intelligentsia salvia mustache 90's code editing brunch. Butcher polaroid VHS art party, hashtag Brooklyn deep v PBR narwhal sustainable mixtape swag wolf squid tote bag. Tote bag cronut semiotics,</p><button class="btn btn-flat pink accent-3 waves-effect waves-light white-text">Readmore <i class="material-icons right">send</i></button><button class="btn btn-flat purple darken-4 waves-effect waves-light white-text">Edit <i class="material-icons right">mode_edit</i></button><button class="btn btn-flat red darken-4 waves-effect waves-light white-text">Delete <i class="material-icons right">delete</i></button></div></div><div class="row"><div class="col s12"><h5>Here the title</h5><div class="divider"></div><p>Sriracha biodiesel taxidermy organic post-ironic, Intelligentsia salvia mustache 90's code editing brunch. Butcher polaroid VHS art party, hashtag Brooklyn deep v PBR narwhal sustainable mixtape swag wolf squid tote bag. Tote bag cronut semiotics,</p><button class="btn btn-flat pink accent-3 waves-effect waves-light white-text">Readmore <i class="material-icons right">send</i></button><button class="btn btn-flat purple darken-4 waves-effect waves-light white-text">Edit <i class="material-icons right">mode_edit</i></button><button class="btn btn-flat red darken-4 waves-effect waves-light white-text">Delete <i class="material-icons right">delete</i></button></div></div></div><div class="fixed-action-btn horizontal" style="bottom: 45px; right: 24px;"><a class="btn-floating btn-large red"><i class="large material-icons">add</i></a></div>@endsection
- Turn on the server (‘php artisan serve’) and see the look (http://localhost:8000/)

- Setting database! Modify .env file in /crud-materialize/ directory to set the database setting:
123456DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=crud-materializeDB_USERNAME=your-usernameDB_PASSWORD=your-password
Now we’re not going to use phpmyadmin to create the database. We’ll do it by ‘php artisan migrate’ commandI dont know how to do it and it seems more complicated than I expected so I create the database ‘crud-materialize’ (collation: utf8-general-ci) through phpmyadmin. - Create a new table ‘crud’
12teddy@teddy-K43SJ:~/Documents/works/laravel/crud-materialize$ php artisan make:migration create_crud_table --create=crudCreated Migration: 2016_10_29_030815_create_crud_table
Check /database/migrations/ directory for the script to create ‘crud’ table (2016_10_29_030815_create_crud_table.php). It’d also create two more scripts to create ‘users’ (2014_10_12_000000_create_users_table.php) and ‘password_reset’ table (2014_10_12_100000_create_password_resets_table.php) automatically (if they are not existed yet!). It’s safe to remove its or leave its because we only focus on the ‘crud’ table. - Edit 2016_10_29_030815_create_crud_table.php to add two more fields (‘title’ and ‘content’).
Defaultly, there are two fields available in the file, they are ‘id’ and timestamps. Just insert the above two more fields between them
123456789public function up(){Schema::create('crud', function (Blueprint $table) {$table->increments('id');$table->string('title');$table->text('content');$table->timestamps();});} - Migrate (push) the tables to our database
12345teddy@teddy-K43SJ:~/Documents/works/laravel/crud-materialize$ php artisan migrateMigration table created successfully.Migrated: 2014_10_12_000000_create_users_tableMigrated: 2014_10_12_100000_create_password_resets_tableMigrated: 2016_10_29_030815_create_crud_table
Check those tables in ‘crud-materialize’ database. - Create a new model ‘Crud’
12teddy@teddy-K43SJ:~/Documents/works/laravel/crud-materialize$ php artisan make:model CrudModel created successfully.
Check a new file ‘Crud.php’ in /app/ directory! - Modify Crud.php like this:
1234567class Crud extends Model{protected $table = 'crud';protected $primaryKey = 'id';protected $fillable = ['title','content'];public $timestamps = true;}
Then create a new data in ‘crud’ table via phpmyadmin:
‘title’: ‘Title 1’
‘content’: ‘Content 1 Content 1 Content 1 Content 1 Content 1’ - Retrieve the new data through CrudController
12345678910111213...use App\Crud;class CrudController extends Controller{public function index(){$data=Crud::orderBy('id','DESC')->paginate(10);//return view('show');return view('show')->with('data',$data);}...}
We’ll throw the ‘data’ into our view ‘show’. - Modify show.blade.php in /resources/views/ to get and show the data from CrudController above
123456789101112131415161718...<div class="section">@foreach($data as $d)<div class="row"><div class="col s12"><h5>{{$d->title}}</h5><div class="divider"></div><p>{!!substr($d->content,0,100) !!}...</p><button class="btn btn-flat pink accent-3 waves-effect waves-light white-text">Readmore <i class="material-icons right">send</i></button><button class="btn btn-flat purple darken-4 waves-effect waves-light white-text">Edit <i class="material-icons right">mode_edit</i></button><button class="btn btn-flat red darken-4 waves-effect waves-light white-text">Delete <i class="material-icons right">delete</i></button></div></div>@endforeach</div>...
We use ‘foreach’ loop, so just use one ‘row’ class and remove the others two. - Test!

- Now we want to make the Add, Edit and Delete buttons can be functioned properly. For the Add function, modify /app/Http/Controllers/CrudController.php at ‘create’ function to view ‘add’:
1234public function create(){return view('add');}
Then create a new route for this in /routes/web.app:
1Route::get('/add','CrudController@create');
Create a new blade file ‘add.blade.php’ in /resources/views/ to show the form:
123456789101112131415161718192021222324252627@extends('layouts.index')@section('content')<div class="section"><div class="card-panel purple darken-3 white-text">Tutorial - CRUD Laravel With Materializecss</div></div><div class="section"><form action="{{ url('store') }}" method="POST">{{ csrf_field() }}<div class="row"><div class="input-field col s12"><input type="text" class="validate" name="title"><label for="title">Title</label></div></div><div class="row"><div class="input-field col s12"><textarea id="textarea1" class="materialize-textarea" name="content"></textarea><label for="textarea1">Content</label></div></div><button type="submit" class="btn btn-flat pink accent-3 waves-effect waves-light white-text right">Submit <i class="material-icons right">send</i></button></form></div>@endsection
In ‘show.blade.php’ we can add an url to ‘add’ route when anyone click the ‘add’ button:
1234567...<div class="fixed-action-btn horizontal" style="bottom: 45px; right: 24px;"><a class="btn-floating btn-large red" href="{{url('add')}}"><i class="large material-icons">add</i></a></div>...
OK. Here is the add form when we click the add (+) button (http://localhost:8000/add)
Now we’re going to make ‘Submit’ button work. First, add a new route for ‘store’ in /routes/web.app. ATTENTION! Here we use POST (Route::post) NOT GET (Route::get):
1Route::post('/store','CrudController@store');
Then modify ‘store’ function in /app/Http/Controllers/CrudController.php to validate and store the form:
1234567891011121314public function store(Request $request){$this->validate($request, ['title'=>'required','content'=>'required']);$add=new Crud();$add->title=$request['title'];$add->content=$request['content'];$add->save();return redirect()->to('/');}
OK. Try to add a new data (http://localhost:8000/add)
Here is the result
- Show individual data. We want to show the data if anyone click ‘Readmore’ button.
Add a new route ‘read’ that need ‘id’ parameter in /routes/web.app:
1Route::get('/read/{id}','CrudController@show');
Apply the route at ‘Readmore’ link in /resources/views/show.blade.php:
1<a href="{{url('read',$d->id)}}" class="btn btn-flat pink accent-3 waves-effect waves-light white-text">Readmore <i class="material-icons right">send</i></a>
Modify ‘show’ function in /app/Http/Controllers/CrudController.php to get the data based on id and show the data by throwing it to our new view ‘showdata’:
12345public function show($id){$show=Crud::find($id);return view('showdata')->with('show',$show);}
Create a new blade file ‘showdata.blade.php’ in /resources/views/ like this:
1234567891011121314151617181920212223@extends('layouts.index')@section('content')<div class="section"><div class="card-panel purple darken-3 white-text">Tutorial - CRUD Laravel With Materializecss</div></div><div class="section"><div class="row"><div class="col s12"><h5>{{ $show->title }}</h5><div class="divider"></div><p>{!! $show->content !!}</p><a href="{{url('/')}}" class="btn btn-flat pink accent-3 waves-effect waves-light white-text">Back <i class="material-icons right">undo</i></a></div></div></div>@endsection
OK. Test it by clicking ‘Readmore’ or directly by url like http://localhost:8000/read/2
I added a new ‘Back’ button. please see the complete materialize icon. Click ‘Back’ button to redirect back to the homepage. - Pagination. To show the pagination, we need to add more data. Just use ‘add’ button. Now we want to show just two data per page. So modify ‘index’ function in /app/Http/Controllers/CrudController.php like this:
12345public function index(){$data=Crud::orderBy('id','DESC')->paginate(2); //display 2 data per pagereturn view('show')->with('data',$data);}
To show the pagination counter and the pages, modify /resources/views/show.blade.php to add ‘{{$data->render()}}’ just before @endsection:
123...{{$data->render()}}@endsection
Here is the result (the url would be like http://localhost:8000/?page=1):
- Edit data.
Create two new routes in /routes/web.php. the first to edit the data and the last to update the changes:
12Route::get('/edit/{id}','CrudController@edit');Route::post('/update/{id}','CrudController@update');
Modify ‘edit’ and ‘update’ function in /app/Http/Controllers/CrudController.php:
123456789101112131415161718...public function edit($id){//$data=Crud::find($id); //SAME WITH BELOW$data=Crud::where('id',$id)->first();return view('edit')->with('data',$data);}...public function update(Request $request, $id){$update=Crud::where('id',$id)->first();$update->title=$request['title'];$update->content=$request['content'];$update->update();return redirect()->to('/');}...
Then create a new blade file ‘edit.blade.php’ in /resources/views/. this file basically same with ‘add.blade.php’ but the form url and the input values are different:
12345678910111213141516171819202122232425262728@extends('layouts.index')@section('content')<div class="section"><div class="card-panel purple darken-3 white-text">Tutorial - CRUD Laravel With Materializecss</div></div><div class="section"><form action="{{ url('update',$data->id) }}" method="POST">{{ csrf_field() }}<div class="row"><div class="input-field col s12"><input type="text" class="validate" name="title" value="{{$data->title}}"><label for="title">Title</label></div></div><div class="row"><div class="input-field col s12"><textarea id="textarea1" class="materialize-textarea" name="content">{{$data->content}}</textarea><label for="textarea1">Content</label></div></div><a href="{{url('/')}}" class="btn btn-flat purple accent-3 waves-effect waves-light white-text">Back <i class="material-icons right">undo</i></a><button type="submit" class="btn btn-flat pink accent-3 waves-effect waves-light white-text right">Submit <i class="material-icons right">send</i></button></form></div>@endsection
Dont forget to modify ‘Edit’ button/link in ‘show.blade.php’ to add the ‘edit’ route:
123...<a href="{{url('edit',$d->id)}}" class="btn btn-flat purple darken-4 waves-effect waves-light white-text">Edit <i class="material-icons right">mode_edit</i></a>...
- Delete data.
Create a new route ‘delete’ in /routes/web.php:
1Route::get('/delete/{id}','CrudController@destroy');
Then modify ‘destroy’ function in /app/Http/Controllers/CrudController.php to delete the data:
1234567public function destroy($id){$delete=Crud::find($id);$delete->delete();return redirect()->to('/');}
Modify ‘Delete’ button/link in /resources/views/show.blade.php to apply the delete route and give javascript confirmation about the deletion:
1<a href="{{url('delete',$d->id)}}" onclick="return confirm('Are you sure to delete this data?')" class="btn btn-flat red darken-4 waves-effect waves-light white-text">Delete <i class="material-icons right">delete</i></a>
FINISH!
NEXT: Add User authentication and comment section! - User Authentication.
Use default scaffolding ‘auth’
12teddy@teddy-K43SJ:~/Documents/works/laravel/crud-materialize$ php artisan make:authAuthentication scaffolding generated successfully.
Like I said before, it’ll create user authentication (login, register, password, etc) automatically. Please check the views in /resources/views/auth/ directory!
Also check the routes in /routes/web.php. It’ll create two new routes:
1234...Auth::routes();Route::get('/home', 'HomeController@index');
About this route ‘Auth::routes()’, from http://stackoverflow.com/questions/39196968/laravel-5-3-new-authroutes/39197278#39197278, it said
1Auth::routes() is just a helper class that helps you generate all the routes required for user authentication. You can browse the code here https://github.com/laravel/framework/blob/5.3/src/Illuminate/Routing/Router.php instead.
More read https://laracasts.com/discuss/channels/laravel/laravel-53-routing-as-authroutes?page=1. - Modify /resources/views/layouts/header.blade.php, to add new links ‘login’ and ‘register’:
1234567<ul class="right hide-on-med-and-down"><li><a href="{{ url('/')}}">Home</a></li>@if(Route::has('login'))<li><a href="{{ url('/login')}}">Login</a></li><li><a href="{{ url('/register')}}">Register</a></li>@endif</ul>
Here is the looks
Click ‘Login’ link, it’d display the login page. But we can see the layout (header, color, etc) is different with our homepage. - Edit /resources/views/auth/login.blade.php.
Replace the first line ‘@extends(‘layouts.app’)’ with ‘@extends(‘layouts.index’)’. When we refresh our website, the header show the same layout with our homepage. But the others element are still different. ‘auth’ scaffolding create the views based on bootstrap css but we use materialize css for homepage.
Modify login.blade.php to add some elements like validation, error,etc like this: NOTE: somehow {!! csrf_field() !!} DIDN’T WORK (verifycsrftoken error) SO I WRITE {{ csrf_field() }}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950@extends('layouts.index')@section('content')<div class="section"><div class="card-panel purple darken-3 white-text">Tutorial - CRUD Laravel With Materializecss</div></div><div class="section"><form id="formValidate" action="{{ url('/login') }}" method="POST">{{ csrf_field() }}<div class="row {{ $errors->has('email') ? ' has-error' : '' }}"><div class="input-field col s6 push-s3"><i class="small material-icons prefix">email</i><input id="email" type="email" class="validate" name="email" value="{{ old('email') }}" data-error=".errorEmail" required><label for="email">E-Mail Address</label><div class="errorEmail">@if ($errors->has('email'))<div class="error">{{ $errors->first('email') }}</div>@endif</div></div></div><div class="row {{ $errors->has('password') ? ' has-error' : '' }}"><div class="input-field col s6 push-s3"><i class="small material-icons prefix">vpn_key</i><input id="password" type="password" class="validate" name="password" data-error=".errorPassword" required><label for="password">Password</label><div class="errorPassword">@if ($errors->has('password'))<div class="error">{{ $errors->first('password') }}</div>@endif</div></div></div><div class="row"><div class="input-field col s6 push-s3"><input id="remember" type="checkbox" class="checkbox" name="remember"><label for="remember">Remember Me</label></div></div><div class="row"><div class="input-field col s6 push-s3"><button type="submit" class="btn btn-flat pink accent-3 waves-effect waves-light white-text">Login <i class="material-icons right">send</i></button><a href="{{url('/password/reset')}}" class="btn btn-flat purple accent-3 waves-effect waves-light white-text">Forgot Your Password? <i class="material-icons right">help</i></a></div></div></form></div>@endsection
The validations need jquery-validation library, so download and put the jquery files (jquery.validate.min.js and additional-methods.min.js) in /public/js/. Then link them in /resources/views/layouts/index.blade.php also write the jquery validation (here i changed the jquery to the newer version 1.11.2). Please read Forms Validation to learn more about the validation form for materialize css.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script><script src="{{asset('js/materialize.min.js')}}"></script><script src="{{asset('js/jquery-validation/jquery.validate.min.js')}}"></script><script src="{{asset('js/jquery-validation/additional-methods.min.js')}}"></script><script type="text/javascript">(function($){$(function(){$('.button-collapse').sideNav();$("#formValidate").validate({rules: {uname: {required: true,minlength: 5},email: {required: true,email:true},password: {required: true,minlength: 5},cpassword: {required: true,minlength: 5,equalTo: "#password"},curl: {required: true,url:true},crole:"required",ccomment: {required: true,minlength: 15},cgender:"required",cagree:"required",},//For custom messagesmessages: {uname:{required: "Enter a username",minlength: "Enter at least 5 characters"},curl: "Enter your website",},errorElement : 'div',errorPlacement: function(error, element) {var placement = $(element).data('error');if (placement) {$(placement).append(error)} else {error.insertAfter(element);}}});}); // end of document ready})(jQuery); // end of jQuery name space</script>
We also need to create a new css file ‘style.css’ in /public/css/ to style the error messages:
123456789101112.input-field div.error {position: relative;top: -1rem;left: 0rem;font-size: 0.8rem;color: #FF4081;margin-left: 3rem;-webkit-transform: translateY(0%);-ms-transform: translateY(0%);-o-transform: translateY(0%);transform: translateY(0%);}
Don’t forget to link the css in /resources/views/layouts/index.blade.php
1234...<link rel="stylesheet" href="{{asset('css/materialize.min.css')}}"><link rel="stylesheet" href="{{asset('css/style.css')}}">...
Here is the result (http://localhost:8000/login)
To find out the materialize icons, see https://material.io/icons/. Note: the naming for displaying the icon for materialize css is pretty tricky. For example to show icon for name/username like ‘account box’, we have to write it with underscore (_). so it should be ‘account_box’:
1<i class="small material-icons prefix">account_box</i>
- Do the same for ‘Register’ link.
Here is the modification for /resources/views/auth/register.blade.php
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162@extends('layouts.index')@section('content')<div class="section"><div class="card-panel purple darken-3 white-text">Register</div></div><div class="section"><form id="formValidate" action="{{ url('/register') }}" method="POST">{{ csrf_field() }}<div class="row {{ $errors->has('name') ? ' has-error' : '' }}"><div class="input-field col s6 push-s3"><i class="small material-icons prefix">account_box</i><input id="name" type="text" class="validate" name="name" value="{{ old('name') }}" data-error=".errorName" required><label for="name">Name</label><div class="errorName">@if ($errors->has('name'))<div class="error">{{ $errors->first('name') }}</div>@endif</div></div></div><div class="row {{ $errors->has('email') ? ' has-error' : '' }}"><div class="input-field col s6 push-s3"><i class="small material-icons prefix">email</i><input id="email" type="email" class="validate" name="email" value="{{ old('email') }}" data-error=".errorEmail" required><label for="email">E-Mail Address</label><div class="errorEmail">@if ($errors->has('email'))<div class="error">{{ $errors->first('email') }}</div>@endif</div></div></div><div class="row {{ $errors->has('password') ? ' has-error' : '' }}"><div class="input-field col s6 push-s3"><i class="small material-icons prefix">lock_outline</i><input id="password" type="password" class="validate" name="password" data-error=".errorPassword" required><label for="password">Password</label><div class="errorPassword">@if ($errors->has('password'))<div class="error">{{ $errors->first('password') }}</div>@endif</div></div></div><div class="row"><div class="input-field col s6 push-s3"><i class="small material-icons prefix">lock_outline</i><input id="password-confirm" type="password" class="validate" name="password_confirmation" data-error=".errorPasswordConfirmation" required><label for="password">Confirm Password</label><div class="errorPasswordConfirmation"></div></div></div><div class="row"><div class="input-field col s6 push-s3"><button type="submit" class="btn btn-flat pink accent-3 waves-effect waves-light white-text">Register <i class="material-icons right">send</i></button></div></div></form></div>@endsection
Here is the looks
We need to modify a few things like the page redirection after the log in and the register. I also notice the dropdown menu to show the logged in user still not correct. For modifying the redirection page, it’s simple. Modify the controllers (LoginController.php and RegisterController.php) in /app/Http/Controllers/Auth/ directory. Set $redirectTo variable to the homepage (‘/’) instead of ‘/home’ like this:
12//protected $redirectTo = '/home';protected $redirectTo = '/';
Then for the dropdown menu, we need to modify /resources/views/layouts/header.blade.php like this:
12345678910111213141516171819202122232425262728293031323334353637383940<nav class="pink accent-3" role="navigation"><div class="nav-wrapper container"><div class="col s12"><a id="logo-container" href="#" class="brand-logo">Laravel</a><ul class="right hide-on-med-and-down"><li><a href="{{ url('/')}}">Home</a></li><!-- Authentication Links -->@if (Auth::guest())<li><a href="{{ url('/login') }}">Login</a></li><li><a href="{{ url('/register') }}">Register</a></li>@else<li><a href="#" class="dropdown-button" data-beloworigin="true" data-activates="dropdown1">{{ Auth::user()->name }} <i class="small material-icons prefix right">arrow_drop_down</i></a><ul id="dropdown1" class="dropdown-content pink accent-3"><li><a href="{{ url('/logout') }}"onclick="event.preventDefault();document.getElementById('logout-form').submit();">Logout</a><form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;">{{ csrf_field() }}</form></li></ul></li>@endif</ul><ul id="nav-mobile" class="side-nav"><li><a href="{{ url('/')}}">Home</a></li></ul><a href="#" data-activates="nav-mobile" class="button-collapse"><i class="material-icons">menu</i></a></div></div></nav>
To find out the complete dropdown function for materialized css, please see http://materializecss.com/dropdown.html and http://demo.geekslabs.com/materialize/v3.1/ui-navbar.html.
I also need to make a slightly modification in /public/css/style.css to make the dropdown display the correct font color:
123.dropdown-content li>a, .dropdown-content li>span {color: #ffffff;}
Here is the looks:
- Now, we want to restrict some functions like ‘Add’, ‘Edit’ and ‘Delete’ can only be proceeded when the user is logged in. So we’re going to check the logged in user (‘Auth::check()’) in /app/Http/Controllers/CrudController.php for some functions ‘create’, ‘edit’ and ‘destroy’ like this: (ref: Authentication and Check if user is logged in):
1234567891011121314151617181920212223242526272829303132...public function create(){if(Auth::check()){return view('add');}else{return redirect()->to('/login');}}...public function edit($id){if(Auth::check()){//$data=Crud::find($id); //SAME WITH BELOW$data=Crud::where('id',$id)->first();return view('edit')->with('data',$data);}else{return redirect()->to('/login');}}...public function destroy($id){if(Auth::check()){$delete=Crud::find($id);$delete->delete();return redirect()->to('/');}else{return redirect()->to('/login');}}
OK. When we click the Add, edit and delete icon/buttons, it’d redirect us to the login page if we haven’t logged in!
NEXT: User access/level, go to / proceed to the aim page after logging in, admin panel and comments!
Fast CRUD With Laravel 5
Source: https://gilacoding.com/read/membuat-crud-laravel-hanya-dengan-5-menit
- Create a new laravel project named ‘latihan-crud’
Type this command: composer create-project –prefer-dist laravel/laravel latihan-crud
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256teddy@teddy-K43SJ:~/Documents/works/laravel$ composer create-project --prefer-dist laravel/laravel latihan-crudWarning: This development build of composer is over 60 days old. It is recommended to update it by running "/usr/local/bin/composer self-update" to get the latest version.Installing laravel/laravel (v5.3.16)- Installing laravel/laravel (v5.3.16)Downloading: 100%Created project in latihan-crud> php -r "file_exists('.env') || copy('.env.example', '.env');"Loading composer repositories with package informationUpdating dependencies (including require-dev)- Installing vlucas/phpdotenv (v2.4.0)Downloading: 100%- Installing symfony/polyfill-mbstring (v1.2.0)Loading from cache- Installing symfony/var-dumper (v3.1.5)Downloading: 100%- Installing symfony/translation (v3.1.5)Downloading: 100%- Installing symfony/routing (v3.1.5)Downloading: 100%- Installing symfony/process (v3.1.5)Downloading: 100%- Installing psr/log (1.0.2)Downloading: 100%- Installing symfony/debug (v3.1.5)Downloading: 100%- Installing symfony/http-foundation (v3.1.5)Downloading: 100%- Installing symfony/event-dispatcher (v3.1.5)Loading from cache- Installing symfony/http-kernel (v3.1.5)Downloading: 100%- Installing symfony/finder (v3.1.5)Downloading: 100%- Installing symfony/console (v3.1.5)Downloading: 100%- Installing swiftmailer/swiftmailer (v5.4.3)Loading from cache- Installing paragonie/random_compat (v2.0.3)Downloading: 100%- Installing ramsey/uuid (3.5.1)Downloading: 100%- Installing jakub-onderka/php-console-color (0.1)Loading from cache- Installing jakub-onderka/php-console-highlighter (v0.3.2)Loading from cache- Installing dnoegel/php-xdg-base-dir (0.1)Loading from cache- Installing nikic/php-parser (v2.1.1)Downloading: 100%- Installing psy/psysh (v0.7.2)Loading from cache- Installing nesbot/carbon (1.21.0)Loading from cache- Installing mtdowling/cron-expression (v1.1.0)Loading from cache- Installing monolog/monolog (1.21.0)Loading from cache- Installing league/flysystem (1.0.32)Downloading: 100%- Installing symfony/polyfill-util (v1.2.0)Loading from cache- Installing symfony/polyfill-php56 (v1.2.0)Loading from cache- Installing jeremeamia/superclosure (2.2.0)Loading from cache- Installing doctrine/inflector (v1.1.0)Loading from cache- Installing classpreloader/classpreloader (3.0.0)Loading from cache- Installing laravel/framework (v5.3.19)Downloading: 100%- Installing fzaninotto/faker (v1.6.0)Loading from cache- Installing hamcrest/hamcrest-php (v1.2.2)Loading from cache- Installing mockery/mockery (0.9.5)Loading from cache- Installing symfony/yaml (v3.1.5)Downloading: 100%- Installing sebastian/version (2.0.0)Downloading: 100%- Installing sebastian/resource-operations (1.0.0)Downloading: 100%- Installing sebastian/recursion-context (1.0.2)Loading from cache- Installing sebastian/object-enumerator (1.0.0)Downloading: 100%- Installing sebastian/global-state (1.1.1)Loading from cache- Installing sebastian/exporter (1.2.2)Loading from cache- Installing sebastian/environment (1.3.8)Downloading: 100%- Installing sebastian/diff (1.4.1)Loading from cache- Installing sebastian/comparator (1.2.0)Loading from cache- Installing doctrine/instantiator (1.0.5)Loading from cache- Installing phpunit/php-text-template (1.2.1)Loading from cache- Installing phpunit/phpunit-mock-objects (3.4.0)Downloading: 100%- Installing phpunit/php-timer (1.0.8)Loading from cache- Installing phpunit/php-file-iterator (1.4.1)Loading from cache- Installing sebastian/code-unit-reverse-lookup (1.0.0)Downloading: 100%- Installing phpunit/php-token-stream (1.4.8)Loading from cache- Installing phpunit/php-code-coverage (4.0.1)Downloading: 100%- Installing webmozart/assert (1.1.0)Downloading: 100%- Installing phpdocumentor/reflection-common (1.0)Loading from cache- Installing phpdocumentor/type-resolver (0.2)Loading from cache- Installing phpdocumentor/reflection-docblock (3.1.1)Downloading: 100%- Installing phpspec/prophecy (v1.6.1)Loading from cache- Installing myclabs/deep-copy (1.5.4)Downloading: 100%- Installing phpunit/phpunit (5.6.1)Downloading: 100%- Installing symfony/css-selector (v3.1.5)Downloading: 100%- Installing symfony/dom-crawler (v3.1.5)Downloading: 100%symfony/var-dumper suggests installing ext-symfony_debug ()symfony/translation suggests installing symfony/config ()symfony/routing suggests installing doctrine/annotations (For using the annotation loader)symfony/routing suggests installing symfony/config (For using the all-in-one router or any loader)symfony/routing suggests installing symfony/dependency-injection (For loading routes from a service)symfony/routing suggests installing symfony/expression-language (For using expression matching)symfony/event-dispatcher suggests installing symfony/dependency-injection ()symfony/http-kernel suggests installing symfony/browser-kit ()symfony/http-kernel suggests installing symfony/class-loader ()symfony/http-kernel suggests installing symfony/config ()symfony/http-kernel suggests installing symfony/dependency-injection ()paragonie/random_compat suggests installing ext-libsodium (Provides a modern crypto API that can be used to generate random bytes.)ramsey/uuid suggests installing ircmaxell/random-lib (Provides RandomLib for use with the RandomLibAdapter)ramsey/uuid suggests installing ext-libsodium (Provides the PECL libsodium extension for use with the SodiumRandomGenerator)ramsey/uuid suggests installing ext-uuid (Provides the PECL UUID extension for use with the PeclUuidTimeGenerator and PeclUuidRandomGenerator)ramsey/uuid suggests installing moontoast/math (Provides support for converting UUID to 128-bit integer (in string form).)ramsey/uuid suggests installing ramsey/uuid-doctrine (Allows the use of Ramsey\Uuid\Uuid as Doctrine field type.)ramsey/uuid suggests installing ramsey/uuid-console (A console application for generating UUIDs with ramsey/uuid)psy/psysh suggests installing ext-pdo-sqlite (The doc command requires SQLite to work.)monolog/monolog suggests installing aws/aws-sdk-php (Allow sending log messages to AWS services like DynamoDB)monolog/monolog suggests installing doctrine/couchdb (Allow sending log messages to a CouchDB server)monolog/monolog suggests installing ext-amqp (Allow sending log messages to an AMQP server (1.0+ required))monolog/monolog suggests installing ext-mongo (Allow sending log messages to a MongoDB server)monolog/monolog suggests installing graylog2/gelf-php (Allow sending log messages to a GrayLog2 server)monolog/monolog suggests installing mongodb/mongodb (Allow sending log messages to a MongoDB server via PHP Driver)monolog/monolog suggests installing php-amqplib/php-amqplib (Allow sending log messages to an AMQP server using php-amqplib)monolog/monolog suggests installing php-console/php-console (Allow sending log messages to Google Chrome)monolog/monolog suggests installing rollbar/rollbar (Allow sending log messages to Rollbar)monolog/monolog suggests installing ruflin/elastica (Allow sending log messages to an Elastic Search server)monolog/monolog suggests installing sentry/sentry (Allow sending log messages to a Sentry server)league/flysystem suggests installing league/flysystem-aws-s3-v2 (Allows you to use S3 storage with AWS SDK v2)league/flysystem suggests installing league/flysystem-aws-s3-v3 (Allows you to use S3 storage with AWS SDK v3)league/flysystem suggests installing league/flysystem-azure (Allows you to use Windows Azure Blob storage)league/flysystem suggests installing league/flysystem-cached-adapter (Flysystem adapter decorator for metadata caching)league/flysystem suggests installing league/flysystem-copy (Allows you to use Copy.com storage)league/flysystem suggests installing league/flysystem-dropbox (Allows you to use Dropbox storage)league/flysystem suggests installing league/flysystem-eventable-filesystem (Allows you to use EventableFilesystem)league/flysystem suggests installing league/flysystem-rackspace (Allows you to use Rackspace Cloud Files)league/flysystem suggests installing league/flysystem-sftp (Allows you to use SFTP server storage via phpseclib)league/flysystem suggests installing league/flysystem-webdav (Allows you to use WebDAV storage)league/flysystem suggests installing league/flysystem-ziparchive (Allows you to use ZipArchive adapter)laravel/framework suggests installing aws/aws-sdk-php (Required to use the SQS queue driver and SES mail driver (~3.0).)laravel/framework suggests installing doctrine/dbal (Required to rename columns and drop SQLite columns (~2.4).)laravel/framework suggests installing guzzlehttp/guzzle (Required to use the Mailgun and Mandrill mail drivers and the ping methods on schedules (~5.3|~6.0).)laravel/framework suggests installing league/flysystem-aws-s3-v3 (Required to use the Flysystem S3 driver (~1.0).)laravel/framework suggests installing league/flysystem-rackspace (Required to use the Flysystem Rackspace driver (~1.0).)laravel/framework suggests installing pda/pheanstalk (Required to use the beanstalk queue driver (~3.0).)laravel/framework suggests installing predis/predis (Required to use the redis cache and queue drivers (~1.0).)laravel/framework suggests installing pusher/pusher-php-server (Required to use the Pusher broadcast driver (~2.0).)laravel/framework suggests installing symfony/psr-http-message-bridge (Required to use psr7 bridging features (0.2.*).)sebastian/global-state suggests installing ext-uopz (*)phpunit/phpunit-mock-objects suggests installing ext-soap (*)phpunit/php-code-coverage suggests installing ext-xdebug (>=2.4.0)phpunit/phpunit suggests installing phpunit/php-invoker (~1.1)phpunit/phpunit suggests installing ext-xdebug (*)Writing lock fileGenerating autoload files> Illuminate\Foundation\ComposerScripts::postUpdate> php artisan optimizeGenerating optimized class loaderThe compiled class file has been removed.> php artisan key:generateApplication key [base64:2uccC5SynOBfgPZAA1zWrAQRWroPmxdMxnCT0KkXSew=] set successfully.
- Modify .env file in /laravel/latihan-crud/ directory to set the database setting:
123456DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=latihan-crudDB_USERNAME=(your db username)DB_PASSWORD=(your db password) - Create the new database ‘latihan-crud’ on phpmyadmin
- Install new package ‘crud-generator’ from ‘appzcoder’: composer require appzcoder/crud-generator
DONT FORGET TO GO INTO ‘latihan-crud’ DIRECTORY FIRST!
1234567891011121314teddy@teddy-K43SJ:~/Documents/works/laravel/latihan-crud$ composer require appzcoder/crud-generatorUsing version ^1.2 for appzcoder/crud-generator./composer.json has been updatedLoading composer repositories with package informationUpdating dependencies (including require-dev)- Installing appzcoder/crud-generator (v1.2.2)Loading from cacheWriting lock fileGenerating autoload files> Illuminate\Foundation\ComposerScripts::postUpdate> php artisan optimizeGenerating optimized class loaderThe compiled class file has been removed.
Look up ‘appzcoder’ directory in /latihan-crud/vendor/ - Add the new package ‘Appzcoder\CrudGenerator\CrudGeneratorServiceProvider::class’ in /config/app.php in ‘providers’
12345678910111213141516171819202122...'providers' => [/** Laravel Framework Service Providers...*/...Illuminate\View\ViewServiceProvider::class,/** Package Service Providers...*////** Application Service Providers...*/...App\Providers\RouteServiceProvider::class,Appzcoder\CrudGenerator\CrudGeneratorServiceProvider::class,],
- Install another package ‘laravelcollective/html’
1234567891011121314teddy@teddy-K43SJ:~/Documents/works/laravel/latihan-crud$ composer require laravelcollective/htmlUsing version ^5.3 for laravelcollective/html./composer.json has been updatedLoading composer repositories with package informationUpdating dependencies (including require-dev)- Installing laravelcollective/html (v5.3.0)Downloading: 100%Writing lock fileGenerating autoload files> Illuminate\Foundation\ComposerScripts::postUpdate> php artisan optimizeGenerating optimized class loaderThe compiled class file has been removed.
Then do the same with #5 to add the new package ‘Collective\Html\HtmlServiceProvider::class,’ in /config/app.php in ‘providers’:
123456789101112131415161718192021'providers' => [/** Laravel Framework Service Providers...*/...Illuminate\View\ViewServiceProvider::class,/** Package Service Providers...*////** Application Service Providers...*/...Appzcoder\CrudGenerator\CrudGeneratorServiceProvider::class,Collective\Html\HtmlServiceProvider::class,],
- In the same file (app.php), add the new facades ‘Form’ and ‘HTML’ (????) in ‘aliases’ section:
12345678910...'aliases' => [...,'Form' => Collective\Html\FormFacade::class,...'HTML' => Collective\Html\HtmlFacade::class,...], - Do ‘composer update’ to update the dependencies
123456789teddy@teddy-K43SJ:~/Documents/works/laravel/latihan-crud$ composer updateLoading composer repositories with package informationUpdating dependencies (including require-dev)Nothing to install or updateGenerating autoload files> Illuminate\Foundation\ComposerScripts::postUpdate> php artisan optimizeGenerating optimized class loaderThe compiled class file has been removed. - Then publish our files and setting
1234567teddy@teddy-K43SJ:~/Documents/works/laravel/latihan-crud$ php artisan vendor:publishCopied Directory [/vendor/laravel/framework/src/Illuminate/Notifications/resources/views] To [/resources/views/vendor/notifications]Copied Directory [/vendor/laravel/framework/src/Illuminate/Pagination/resources/views] To [/resources/views/vendor/pagination]Copied File [/vendor/appzcoder/crud-generator/config/crudgenerator.php] To [/config/crudgenerator.php]Copied File [/vendor/appzcoder/crud-generator/publish/app.blade.php] To [/resources/views/layouts/app.blade.php]Copied Directory [/vendor/appzcoder/crud-generator/src/stubs] To [/resources/crud-generator]Publishing complete for tag []! - Create a new class ‘Posts’ for our crud generator with two fields ‘title’ and
<OLD>
1php artisan crud:generate Posts --fields="title#string, body#text"
BUT I GOT THIS ERROR:
12345678teddy@teddy-K43SJ:~/Documents/works/laravel/latihan-crud$ php artisan crud:generate Posts --fields="title#string, body#text"Controller created successfully.Model created successfully.Migration created successfully.[ErrorException]Undefined index: string, body
</OLD
<NEW>
From this https://packagist.org/packages/appzcoder/crud-generator, I found the source of the error, I supposed to use ‘;’ (“title#string; body#text”) instead of ‘,’ (“title#string, body#text”) between the fields like this (DONT USE THIS COMMAND. THIS IS ONLY JUST A CORRECT COMMAND)
123456teddy@teddy-K43SJ:~/Documents/works/laravel/latihan-crud$ php artisan crud:generate Posts --fields="title#string; content#text; category#select#options=technology,tips,health" --view-path=admin --controller-namespace=Admin --route-group=adminController created successfully.Model already exists!Migration created successfully.View created successfully.Crud/Resource route added to /home/teddy/Documents/works/laravel/latihan-crud/routes/web.php
USE THIS COMMAND INSTEAD TO MAKE IT CONSISTENT WITH THE ORIGINAL TUTORIAL:
123456teddy@teddy-K43SJ:~/Documents/works/laravel/latihan-crud$ php artisan crud:generate Posts --fields="title#string; body#text"Controller already exists!Model already exists!Migration created successfully.View created successfully.Crud/Resource route added to /home/teddy/Documents/works/laravel/latihan-crud/routes/web.php
</NEW>
The script for the table migration would be exist in /database/migrations/ directory (IF YOU FIND MORE THAN ONE SCRIPT WITH SAME TABLE ‘Posts’ LIKE ‘2016_10_22_081014_create_posts_table.php’ AND ‘2016_10_22_074719_create_posts_table.php’, PLS REMOVE THE OLD ONE FIRST! OR WE’D GET THIS ERROR: “Cannot declare class CreatePostsTable, because the name is already in use”)
1234567teddy@teddy-K43SJ:~/Documents/works/laravel/latihan-crud$ php artisan migrateMigration table created successfully.PHP Fatal error: Cannot declare class CreatePostsTable, because the name is already in use in /home/teddy/Documents/works/laravel/latihan-crud/database/migrations/2016_10_22_075907_create_posts_table.php on line 33[Symfony\Component\Debug\Exception\FatalErrorException]Cannot declare class CreatePostsTable, because the name is already in use - Push the table script to our database with ‘php artisan migrate’
123teddy@teddy-K43SJ:~/Documents/works/laravel/latihan-crud$ php artisan migrateMigrated: 2014_10_12_000000_create_users_tableMigrated: 2014_10_12_100000_create_password_resets_tableMigrated: 2016_10_22_081014_create_posts_table
Check our database to make sure the new table ‘posts’ is already created! SOMEHOW THE OTHERS TABLES ‘migrations’, ‘users’ AND ‘password_resets’ ARE CREATED ALSO! - Test on the browser. Start the server: ‘php artisan serve’ then open on our browser : http://localhost:8000/ –> It shows the laravel welcome page!
Remember, A new route ‘posts’ is already created automatically from previous step, so to see the CRUD in action, pls go to http://localhost:8000/posts
- Add new data.
Click the ‘+’ blue icon
then fill the form with the fields ‘Title’ and ‘Body’. Then press ‘Create’ Button
But I got this error:
1SQLSTATE[HY000]: General error: 1364 Field 'body' doesn't have a default value (SQL: insert into `posts` (`title`, `updated_at`, `created_at`) values (Title 1, 2016-10-22 09:27:24, 2016-10-22 09:27:24))
I found the solution! In ‘Post’ class in /app/Post.php, at ‘$fillable’ variable, It’s only has ‘title’ field But there is no ‘body’ field!
12345678910111213class Post extends Model{.../*** Attributes that should be mass-assignable.** @var array*/protected $fillable = ['title'];}
So add ‘body’ field like this:
123456789101112class Post extends Model{.../*** Attributes that should be mass-assignable.** @var array*/protected $fillable = ['title','body'];}
Then repeat the creation of new data! Here is the expected result
Membuat Login Laravel 5 2 dengan username dan Hak akses - At the right top of the page, there are two links ‘login’ and ‘register’ but none of them are working. To make them work, we need to create the authentication to create users like this: php artisan make:auth
12teddy@teddy-K43SJ:~/Documents/works/laravel/latihan-crud$ php artisan make:authAuthentication scaffolding generated successfully.
Dont forget to stop the server first by clicking CTRL+C!
The above command would create some views for login, register, password, etc. Please check them in /resources/views/auth/ directory!
This also create automatically a few new routes in /routes/web.php
1234...Auth::routes();Route::get('/home', 'HomeController@index'); - Now we can try them on our browser
Remember, we dont need to create/migrate the user table because we already did this at the previous step (#11) when we did the first migration!
Now the links ‘login’ and ‘register’ are working!
Here is the register page: http://localhost:8000/register
I use password: satria. Successful registration would be redirected to http://localhost:8000/home
The links ‘login’ and ‘register’ also be showed up on the initial page http://localhost:8000/ - Change/set default route ‘/’
In /routes/web.php, the default route for http://localhost:8000/ would go to the welcome page in /resources/views/welcome.blade.php. Here is the default route
123Route::get('/', function () {return view('welcome');});
We want to change it to go to our login page! We have the login page in /resources/views/auth/login.blade.php. So here is the modified route
12345Route::get('/', function () {//return view('welcome');return view('auth/login');//return redirect()->route('posts');});
Now each our homepage http://localhost:8000/ is opened, it’d open the login page!
If we want to set the default route to the post page, please modify /routes/web.php like this:
1Route::get('/', 'PostsController@index');
Now, if we open http://localhost:8000/, it’d show the list of the post page!
LEARN ALSO THIS:
Laravel Admin Panel
An admin panel for managing users, roles, permissions & crud.
Install Laravel 5 On Ubuntu 14.04
References:
1. https://www.howtoforge.com/tutorial/install-laravel-on-ubuntu-for-apache/
2. https://laravel.com/docs/5.2
How to install:
- Laravel uses composer much for installation. So first check the composer version (I already installed the composer) through the terminal.
1teddy@teddy-K43SJ:~$ composer --version
Here is the result for my system.
123You are running composer with xdebug enabled. This has a major impact on runtime performance. See https://getcomposer.org/xdebugWarning: This development build of composer is over 60 days old. It is recommended to update it by running "/usr/local/bin/composer self-update" to get the latest version.Composer version 1.0-dev (6eb50623e6e00bac4ed893802836e50b62c83434) 2016-02-08 19:03:10
My composer version is 1.0-dev. It says my composer version is over 60 days old. Let update it.
1teddy@teddy-K43SJ:~$ composer self-update
But the result shows complain about permission.
123[ErrorException]rename(/home/teddy/.composer/cache/composer-temp.phar,/usr/local/bin/composer): Permission denied
Here we need ‘sudo’ to update it.
1teddy@teddy-K43SJ:~$ sudo composer self-update
Here is the success result.
Okay. Lets check it again.
My latest composer version is 1.2-dev. - Ready to install Laravel. First I need to go in laravel directory in Documents/works/. Then there are two ways how to install it. They are ‘Laravel Installer’ and ‘composer create-project’. Somehow Laravel Doc mention the installer first. I dont know which one is the best but this QA from stackoverflow can give a perspective. First I used ‘composer create-project’ way to create a new project ‘mylaravelproject’. Here is the installation:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232teddy@teddy-K43SJ:~$ cd Documents/works/laravel/teddy@teddy-K43SJ:~/Documents/works/laravel$ composer create-project --prefer-dist laravel/laravel mylaravelprojectYou are running composer with xdebug enabled. This has a major impact on runtime performance. See https://getcomposer.org/xdebugInstalling laravel/laravel (v5.2.31)- Installing laravel/laravel (v5.2.31)Downloading: 100%Created project in mylaravelproject> php -r "copy('.env.example', '.env');"Loading composer repositories with package informationUpdating dependencies (including require-dev)- Installing vlucas/phpdotenv (v2.3.0)Downloading: 100%- Installing symfony/polyfill-mbstring (v1.2.0)Downloading: 100%- Installing symfony/var-dumper (v3.0.9)Downloading: 100%- Installing symfony/translation (v3.0.9)Downloading: 100%- Installing symfony/routing (v3.0.9)Downloading: 100%- Installing symfony/process (v3.0.9)Downloading: 100%- Installing symfony/polyfill-util (v1.2.0)Downloading: 100%- Installing symfony/polyfill-php56 (v1.2.0)Downloading: 100%- Installing symfony/http-foundation (v3.0.9)Downloading: 100%- Installing symfony/event-dispatcher (v3.1.3)Downloading: 100%- Installing psr/log (1.0.0)Downloading: 100%- Installing symfony/debug (v3.0.9)Downloading: 100%- Installing symfony/http-kernel (v3.0.9)Downloading: 100%- Installing symfony/finder (v3.0.9)Downloading: 100%- Installing symfony/console (v3.0.9)Downloading: 100%- Installing swiftmailer/swiftmailer (v5.4.3)Downloading: 100%- Installing jakub-onderka/php-console-color (0.1)Downloading: 100%- Installing jakub-onderka/php-console-highlighter (v0.3.2)Downloading: 100%- Installing dnoegel/php-xdg-base-dir (0.1)Downloading: 100%- Installing nikic/php-parser (v2.1.0)Downloading: 100%- Installing psy/psysh (v0.7.2)Downloading: 100%- Installing paragonie/random_compat (v1.4.1)Downloading: 100%- Installing nesbot/carbon (1.21.0)Downloading: 100%- Installing mtdowling/cron-expression (v1.1.0)Downloading: 100%- Installing monolog/monolog (1.21.0)Downloading: 100%- Installing league/flysystem (1.0.26)Downloading: 100%- Installing jeremeamia/superclosure (2.2.0)Downloading: 100%- Installing doctrine/inflector (v1.1.0)Downloading: 100%- Installing classpreloader/classpreloader (3.0.0)Downloading: 100%- Installing laravel/framework (v5.2.42)Downloading: 100%- Installing fzaninotto/faker (v1.6.0)Downloading: 100%- Installing hamcrest/hamcrest-php (v1.2.2)Downloading: 100%- Installing mockery/mockery (0.9.5)Downloading: 100%- Installing symfony/yaml (v3.1.3)Downloading: 100%- Installing sebastian/version (1.0.6)Downloading: 100%- Installing sebastian/global-state (1.1.1)Downloading: 100%- Installing sebastian/recursion-context (1.0.2)Downloading: 100%- Installing sebastian/exporter (1.2.2)Downloading: 100%- Installing sebastian/environment (1.3.7)Downloading: 100%- Installing sebastian/diff (1.4.1)Downloading: 100%- Installing sebastian/comparator (1.2.0)Downloading: 100%- Installing doctrine/instantiator (1.0.5)Downloading: 100%- Installing phpunit/php-text-template (1.2.1)Downloading: 100%- Installing phpunit/phpunit-mock-objects (2.3.8)Downloading: 100%- Installing phpunit/php-timer (1.0.8)Downloading: 100%- Installing phpunit/php-file-iterator (1.4.1)Downloading: 100%- Installing phpunit/php-token-stream (1.4.8)Downloading: 100%- Installing phpunit/php-code-coverage (2.2.4)Downloading: 100%- Installing webmozart/assert (1.0.2)Downloading: 100%- Installing phpdocumentor/reflection-common (1.0)Downloading: 100%- Installing phpdocumentor/type-resolver (0.2)Downloading: 100%- Installing phpdocumentor/reflection-docblock (3.1.0)Downloading: 100%- Installing phpspec/prophecy (v1.6.1)Downloading: 100%- Installing phpunit/phpunit (4.8.27)Downloading: 100%- Installing symfony/css-selector (v3.0.9)Downloading: 100%- Installing symfony/dom-crawler (v3.0.9)Downloading: 100%symfony/var-dumper suggests installing ext-symfony_debug ()symfony/translation suggests installing symfony/config ()symfony/routing suggests installing doctrine/annotations (For using the annotation loader)symfony/routing suggests installing symfony/config (For using the all-in-one router or any loader)symfony/routing suggests installing symfony/dependency-injection (For loading routes from a service)symfony/routing suggests installing symfony/expression-language (For using expression matching)symfony/event-dispatcher suggests installing symfony/dependency-injection ()symfony/http-kernel suggests installing symfony/browser-kit ()symfony/http-kernel suggests installing symfony/class-loader ()symfony/http-kernel suggests installing symfony/config ()symfony/http-kernel suggests installing symfony/dependency-injection ()psy/psysh suggests installing ext-pdo-sqlite (The doc command requires SQLite to work.)paragonie/random_compat suggests installing ext-libsodium (Provides a modern crypto API that can be used to generate random bytes.)monolog/monolog suggests installing aws/aws-sdk-php (Allow sending log messages to AWS services like DynamoDB)monolog/monolog suggests installing doctrine/couchdb (Allow sending log messages to a CouchDB server)monolog/monolog suggests installing ext-amqp (Allow sending log messages to an AMQP server (1.0+ required))monolog/monolog suggests installing ext-mongo (Allow sending log messages to a MongoDB server)monolog/monolog suggests installing graylog2/gelf-php (Allow sending log messages to a GrayLog2 server)monolog/monolog suggests installing mongodb/mongodb (Allow sending log messages to a MongoDB server via PHP Driver)monolog/monolog suggests installing php-amqplib/php-amqplib (Allow sending log messages to an AMQP server using php-amqplib)monolog/monolog suggests installing php-console/php-console (Allow sending log messages to Google Chrome)monolog/monolog suggests installing rollbar/rollbar (Allow sending log messages to Rollbar)monolog/monolog suggests installing ruflin/elastica (Allow sending log messages to an Elastic Search server)monolog/monolog suggests installing sentry/sentry (Allow sending log messages to a Sentry server)league/flysystem suggests installing league/flysystem-aws-s3-v2 (Allows you to use S3 storage with AWS SDK v2)league/flysystem suggests installing league/flysystem-aws-s3-v3 (Allows you to use S3 storage with AWS SDK v3)league/flysystem suggests installing league/flysystem-azure (Allows you to use Windows Azure Blob storage)league/flysystem suggests installing league/flysystem-cached-adapter (Flysystem adapter decorator for metadata caching)league/flysystem suggests installing league/flysystem-copy (Allows you to use Copy.com storage)league/flysystem suggests installing league/flysystem-dropbox (Allows you to use Dropbox storage)league/flysystem suggests installing league/flysystem-eventable-filesystem (Allows you to use EventableFilesystem)league/flysystem suggests installing league/flysystem-rackspace (Allows you to use Rackspace Cloud Files)league/flysystem suggests installing league/flysystem-sftp (Allows you to use SFTP server storage via phpseclib)league/flysystem suggests installing league/flysystem-webdav (Allows you to use WebDAV storage)league/flysystem suggests installing league/flysystem-ziparchive (Allows you to use ZipArchive adapter)laravel/framework suggests installing aws/aws-sdk-php (Required to use the SQS queue driver and SES mail driver (~3.0).)laravel/framework suggests installing doctrine/dbal (Required to rename columns and drop SQLite columns (~2.4).)laravel/framework suggests installing guzzlehttp/guzzle (Required to use the Mailgun and Mandrill mail drivers and the ping methods on schedules (~5.3|~6.0).)laravel/framework suggests installing league/flysystem-aws-s3-v3 (Required to use the Flysystem S3 driver (~1.0).)laravel/framework suggests installing league/flysystem-rackspace (Required to use the Flysystem Rackspace driver (~1.0).)laravel/framework suggests installing pda/pheanstalk (Required to use the beanstalk queue driver (~3.0).)laravel/framework suggests installing predis/predis (Required to use the redis cache and queue drivers (~1.0).)laravel/framework suggests installing pusher/pusher-php-server (Required to use the Pusher broadcast driver (~2.0).)laravel/framework suggests installing symfony/psr-http-message-bridge (Required to psr7 bridging features (0.2.*).)sebastian/global-state suggests installing ext-uopz (*)phpunit/phpunit suggests installing phpunit/php-invoker (~1.1)Writing lock fileGenerating autoload files> Illuminate\Foundation\ComposerScripts::postUpdate> php artisan optimizeGenerating optimized class loader> php artisan key:generateApplication key [base64:ANAqub0Biko5oe7BYFuleX15JW/QbYb3lWvFocHvHyU=] set successfully.
Here is the files and directories are created.
It seems ‘composer create-project’ installation download all the component required to start developing laravel project at one shot! Please see all component in ‘vendor’ directory. Before I try to give a shot on this new installation, I need to set some permission on a few directories suggested on the laravel doc like ‘storage’ and ‘bootstrap/cache’.
12sudo chmod -R 777 storagesudo chmod -R 777 bootstrap/cache/
Now, I am ready to try it on my web browser. Many article suggest to setup a virtual host but I want to test it right away without it. I can use PHP CLI to do that. Here is the command on my linux terminal.
1php -S localhost:8000 -t public
PHP CLI is running.
1234567teddy@teddy-K43SJ:~/Documents/works/laravel/mylaravelproject$ php -S localhost:8000 -t publicPHP 5.6.23-1+deprecated+dontuse+deb.sury.org~trusty+1 Development Server started at Wed Aug 10 10:01:34 2016Listening on http://localhost:8000Document root is /home/teddy/Documents/works/laravel/mylaravelproject/publicPress Ctrl-C to quit.[Wed Aug 10 10:02:03 2016] 127.0.0.1:57295 [200]: /[Wed Aug 10 10:02:03 2016] 127.0.0.1:57296 [200]: /favicon.ico
Open it on the web browser with url:
1http://localhost:8000
Here is the welcome screen.
laravel welcome screen The another way is to use ‘Laravel Installer’. From this stackoverflow QA, this way seems to download just required ‘vendor’ component/bundle. It may be for the expert level that needed more thought about laravel (CMIIW). I hope I can learn it later.
- Setup the virtualhost. after the successful first try, I think it need to setup a virtualhost config so I dont need to run/stop the PHP CLI on my linux terminal everytime when I want to give it a try. First, I need to create a new apache configuration file. I name it ‘mylaravel.conf’.
1sudo gedit /etc/ache2/sites-available/mylaravel.conf
Here is the file content.
123456789101112<VirtualHost *:80>ServerName mylaravelproject.devDocumentRoot /home/teddy/Documents/works/laravel/mylaravelproject/public<Directory /home/teddy/Documents/works/laravel/mylaravelproject>AllowOverride AllRequire all granted</Directory>ErrorLog ${APACHE_LOG_DIR}/error.logCustomLog ${APACHE_LOG_DIR}/access.log combined</VirtualHost>
Make sure the ‘Document root’ path is written correctly. the entry ‘Require all granted’ is required here or I would get an error like this: ‘Forbidden You don’t have permission to access / on this server’. Then I need apache to enable the site and reload it.
12sudo a2ensite mylaravelsudo service apache2 reload
Here is the process.
123456teddy@teddy-K43SJ:~/Documents/works/laravel/mylaravelproject$ sudo a2ensite mylaravelEnabling site mylaravel.To activate the new configuration, you need to run:service apache2 reloadteddy@teddy-K43SJ:~/Documents/works/laravel/mylaravelproject$ sudo service apache2 reload* Reloading Apache httpd web server apache2 *
‘mylaravel’ on ‘sudo a2ensite mylaravel’ is the config file name without .conf extension. then I need to register the site so I can open it through localhost with this command ‘sudo gedit /etc/hosts’.
1teddy@teddy-K43SJ:~/Documents/works/laravel/mylaravelproject$ sudo gedit /etc/hosts
then add this entry in the ‘hosts’ file.
1127.0.0.1 mylaravelproject.dev
then restart the apache server ‘sudo service apache2 restart’. Now I can open it through my web browser with this url: http://mylaravelproject.dev/ - The next step is to learn more about laravel like Application Structure, Configuration, Router, etc. This tutorial Laravel Tutorial and Belajar Laravel Ala Indonesia are worth to be read. I hope I can write my experience on this blog someday.