Home > Article > Backend Development > Laravel 4 primary tutorial - Pages, form validation, laravelpages_PHP tutorial
1. Build Pages management function
Run command:
php artisan generate:controller admin/PagesController
Modify PagesController.php content:
<?php<br />namespace App\Controllers\Admin;<br />use Page;<br />use Input, Notification, Redirect, Sentry, Str;<br />use App\Services\Validators\PageValidator;<br />class PagesController extends \BaseController {<br /> public function index()<br /> {<br /> return \View::make('admin.pages.index')->with('pages', Page::all());<br> }<br> public function show($id)<br> {<br> return \View::make('admin.pages.show')->with('page', Page::find($id))->withAuthor(Sentry::findUserById(Page::find($id)->user_id)->name);<br> }<br> public function create()<br> {<br> return \View::make('admin.pages.create');<br> }<br> public function store()<br> {<br> $validation = new PageValidator;<br> if ($validation->passes())<br> {<br> $page = new Page;<br> $page->title = Input::get('title');<br> $page->body = Input::get('body');<br> $page->user_id = Sentry::getUser()->id;<br> $page->save();<br> Notification::success('新增页面成功!');<br> return Redirect::route('admin.pages.edit', $page->id);<br> }<br> return Redirect::back()->withInput()->withErrors($validation->errors);<br> }<br> public function edit($id)<br> {<br> return \View::make('admin.pages.edit')->with('page', Page::find($id));<br> }<br> public function update($id)<br> {<br> $validation = new PageValidator;<br> if ($validation->passes())<br> {<br> $page = Page::find($id);<br> $page->title = Input::get('title');<br> $page->body = Input::get('body');<br> $page->user_id = Sentry::getUser()->id;<br> $page->save();<br> Notification::success('更新页面成功!');<br> return Redirect::route('admin.pages.edit', $page->id);<br> }<br> return Redirect::back()->withInput()->withErrors($validation->errors);<br> }<br> public function destroy($id)<br> {<br> $page = Page::find($id);<br> $page->delete();<br> Notification::success('删除成功!');<br> return Redirect::route('admin.pages.index');<br> }<br>}
Then, open the http://localhost:8000/admin page and log in with the account and password that were seeded before. We will get an error:
Class App\Controllers\Admin\PagesController does not exist
This file obviously already exists, why does Laravel report an error saying it doesn’t exist? ! The reason is in the second tutorial, so I will explain it directly here. Because this class is not in the top-level namespace, and we did not tell Laravel that we have added a new class in the sub-namespace. Let’s tell it now:
composer dump-autoload
OK, refresh, we will get the following error again:
View [admin.pages.index] not found.
At this time, copy the entire pages folder in my view.
Refresh. You will get the following error:
Class 'Notification' not found
This is because we have not installed the composer package, edvinaskrucas/notification. Please install version 3.0.1 yourself (4 is prepared for Laravel 5). This is the third small job. It must be placed in require. The packages in require-dev are only used during development.
The Notification here is the more useful notification component.
After this is packaged, run:
composer dump-autoload
Then add the following two lines at the appropriate locations in config/app.php:
'Krucas\Notification\NotificationServiceProvider'<br>
'Notification' => 'Krucas\Notification\Facades\Notification'
Many people don’t understand the appropriate position, which leads to many people making mistakes. The solution is also very simple: please refer to my sample code directly: https://github.com/johnlui/Learn-Laravel-4/blob/ master/app/config/app.php
Refresh if you see the following interface:
Congratulations~ The management page of Pages is completed!
2. Form verification
Laravel provides a very easy-to-use native form validation function, but sometimes validation rules need to be reused, so we will use powerful namespaces to achieve code reuse, and will also show PHP naming outside of Laravel With the powerful componentization functions and module decoupling brought by space, HMVC and the like have fallen behind.
Create a new app/services/validators two-level folder, and add at the end of autoload > classmap in composer.json:
"app/services"
This is telling composer: Merge all the files below me and all the files in subfolders into your namespace tree! This allows classes under app/services to declare their own namespace, and files in subfolders can also declare that they belong to the subnamespace. This folder will host our form validation cluster, and of course many other components and modules, for complete decoupling.
After the addition is completed, create a new app/services/validators/Validator.php file:
<?php<br />namespace App\Services\Validators;<br />abstract class Validator {<br /> protected $data;<br /> public $errors;<br /> public static $rules;<br /> public function __construct($data = null)<br /> {<br /> $this->data = $data ?: \Input::all();<br> }<br> public function passes()<br> {<br> $validation = \Validator::make($this->data, static::$rules);<br> if ($validation->passes()) return true;<br> $this->errors = $validation->messages();<br> return false;<br> }<br>}
Create a new app/services/validators/PageValidator.php file:
<?php<br />namespace App\Services\Validators;<br />class PageValidator extends Validator {<br /> public static $rules = array(<br /> 'title' => 'required',<br> 'body' => 'required',<br> );<br>}
Then run:
composer dump-autoload
At this time, you can try all the operations on the entire page! Create, edit, view, delete. At this point, the pages management part is complete!
Big job: At present, the Pages management part has been completed, but the Articles management part still has nothing. Try to imitate the code of Pages and complete a management system similar to Pages. Tip: Include controller, view and form validation. Once you have completed the Articles management part, you will really get started with Laravel!
It can free you from messy codes like noodles; it can help you build a perfect network APP, and every line of code can be concise and expressive. 1. Bundle is the organization form or name of Laravel's expansion package. Laravel's extension package repository is quite mature and can easily help you install extension packages (bundles) into your application. You can choose to download an extension package (bundle) and copy it to the bundles directory, or install it automatically through the command line tool "Artisan". 2. Laravel already has an advanced PHP ActiveRecord implementation -- Eloquent ORM. It can easily apply "constraints" to both sides of the relationship, so that you have complete control over the data and enjoy all the conveniences of ActiveRecord. Eloquent natively supports all methods of the query builder (query-builder) in Fluent. 3. Application logic can be implemented in controllers or directly integrated into route statements, and the syntax is similar to the Sinatra framework. Laravel's design philosophy is to give developers maximum flexibility, allowing them to create very small websites and build large-scale enterprise applications. 4. Reverse Routing gives you the ability to create links (URIs) through route names. Just use the route name and Laravel will automatically create the correct URI for you. This way you can change your routes at any time, and Laravel will automatically update all related links for you. 5. Restful Controllers are an optional way to distinguish GET and POST request logic. For example, in a user login logic, you declare a get_login() action to process the service of obtaining the login page; you also declare a post_login() action to verify the data POSTed from the form, and After validation, a decision is made to redirect to the login page or to the console. 6. Class Auto-loading simplifies the loading of classes. In the future, you no longer need to maintain the auto-loading configuration table and unnecessary component loading. When you want to load any library or model, just use it immediately, and Laravel will automatically load the required files for you. 7. View Composers are essentially a piece of code that is automatically executed when the View is loaded. The best example is the random article recommendation on the side of the blog. The "view assembler" contains the logic for loading the random article recommendation. In this way, you only need to load the view of the content area, and Laravel will do the other things. Complete it automatically for you. 8. The reverse control container (IoC container) provides a convenient way to generate new objects, instantiate objects at any time, and access singleton objects. Inverse control (IoC) means that you almost don't need to load external libraries (libraries), you can access these objects anywhere in the code, and you don't need to endure complicated and redundant code structures. 9. Migrations is like a version control tool, but it manages the database paradigm and is directly integrated into Laravel. You can use the "Artisan" command line tool to generate and execute "migration" instructions. When your team members change the database paradigm, you can easily update the current project through the version control tool, and then execute the "migration command. Well, your database is already up to date! 11. Automatic paging ( Automatic Pagination) function avoids mixing a lot of irrelevant paging configuration code in your business logic. The convenience is that you don’t need to remember the current page... The rest of the text >>
It can free you from messy codes like noodles; it can help you build a perfect network APP, and every line of code can be concise and expressive. 1. Bundle is the organization form or name of Laravel's expansion package. Laravel's extension package repository is quite mature and can easily help you install extension packages (bundles) into your application. You can choose to download an extension package (bundle) and copy it to the bundles directory, or install it automatically through the command line tool "Artisan". 2. Laravel already has an advanced PHP ActiveRecord implementation -- Eloquent ORM. It can easily apply "constraints" to both sides of the relationship, so that you have complete control over the data and enjoy all the conveniences of ActiveRecord. Eloquent natively supports all methods of the query builder (query-builder) in Fluent. 3. Application logic can be implemented in controllers or directly integrated into route statements, and the syntax is similar to the Sinatra framework. Laravel's design philosophy is to give developers maximum flexibility, allowing them to create very small websites and build large-scale enterprise applications. 4. Reverse Routing gives you the ability to create links (URIs) through route names. Just use the route name and Laravel will automatically create the correct URI for you. This way you can change your routes at any time, and Laravel will automatically update all related links for you. 5. Restful Controllers are an optional way to distinguish GET and POST request logic. For example, in a user login logic, you declare a get_login() action to process the service of obtaining the login page; you also declare a post_login() action to verify the data POSTed from the form, and After validation, a decision is made to redirect to the login page or to the console. 6. Class Auto-loading simplifies the loading of classes. In the future, you no longer need to maintain the auto-loading configuration table and unnecessary component loading. When you want to load any library or model, just use it immediately, and Laravel will automatically load the required files for you. 7. View Composers are essentially a piece of code that is automatically executed when the View is loaded. The best example is the random article recommendation on the side of the blog. The "view assembler" contains the logic for loading the random article recommendation. In this way, you only need to load the view of the content area, and Laravel will do the other things. Complete it automatically for you. 8. The reverse control container (IoC container) provides a convenient way to generate new objects, instantiate objects at any time, and access singleton objects. Inverse control (IoC) means that you almost don't need to load external libraries (libraries), you can access these objects anywhere in the code, and you don't need to endure complicated and redundant code structures. 9. Migrations is like a version control tool, but it manages the database paradigm and is directly integrated into Laravel. You can use the "Artisan" command line tool to generate and execute "migration" instructions. When your team members change the database paradigm, you can easily update the current project through the version control tool, and then execute the "migration command. Well, your database is already up to date! 11. Automatic paging ( Automatic Pagination) function avoids mixing a lot of irrelevant paging configuration code in your business logic. The convenience is that you don’t need to remember the current page... The rest of the text >>