laravel6.0 Controller - Resource Controller

Controller:
Controller handles the business should not be processing logic, if it is a small project can be written logic controller, the major points of the project should be pulled out of the business process layer as follows:
services business process layer: for example: Get value, the verification value, exception caught
 
Naming rules:
Controller name: with a large hump named as: HelloController;
Method Name: small hump such as: the helloWorld ();
Member variables: the name of a small hump or _
 
Create a controller (can custom directory):
php artisan make:controller UserController
php artisan make:controller Admin/UserController
 
 
The controller simple and practical examples:
The controller is simple to use:
Database migration
1. Create a database laravel6 configuration database connection
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel6
DB_USERNAME=root
DB_PASSWORD=12345678
2. Detection of the default connection
\config\database.php
   'default' => env('DB_CONNECTION', 'mysql'),
 
3. database migration command:
php artisan migrate
420,001,071 error may occur because the field name to create the table for too long, as resolved
In \ Providers \ AppServiceProvider.php in
 
The controller is simple to use:
Database migration
1. Create a database laravel6 configuration database connection
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel6
DB_USERNAME=root
DB_PASSWORD=12345678
2. Detection of the default connection
\config\database.php
   'default' => env('DB_CONNECTION', 'mysql'),
 
3. database migration command:
php artisan migrate
420,001,071 error may occur because the field name to create the table for too long, as resolved
In \ Providers \ AppServiceProvider.php in
 
Model engineering write
php artisan tinker
Psy Shell v0.9.9 (PHP 7.3.10 — cli) by Justin Hileman
>>> factory(App\User::class,5)->create();
User model data written 5
Database data written 5
 
view view shows
路由:Route::get("show/{id}","UserController@show");
UserController controller written as follows:
public function show($id)
{
    return view("user.profile",["user" => User::findOrNew($id)]);
}
A data transfer id isolated
Create a view \ view \ user \ profile.blade.php
{{$user}}
 
 
 
 
 
Model engineering write
php artisan tinker
Psy Shell v0.9.9 (PHP 7.3.10 — cli) by Justin Hileman
>>> factory(App\User::class,5)->create();
User model data written 5
Database data written 5
 
view view shows
路由:Route::get("show/{id}","UserController@show");
UserController controller written as follows:
public function show($id)
{
    return view("user.profile",["user" => User::findOrNew($id)]);
}
A data transfer id isolated
Create a view \ view \ user \ profile.blade.php
{{$user}}
 
 
Controller loads principles:
In the service provider in RouteServiceProvider.php, you can custom namespace
Different functions and business controllers pulled directory
 
Controller & namespace:
It is important to point out that when defining the route we do not need to specify the full control of the controller namespace. Because `RouteServiceProvider` loads the file route in the routing group that contains a namespace, we only need to command the class name` App \ Http \ part after the namespace Controllers` it.
 
The individual behavior of the controller:
If you want to define controller handles only a single action, you can place a `__invoke` method in the controller:
You can order tool in the `make by Artisan: controller` command` --invokable` option to generate a controller can call:
php artisan make:controller ShowProfile --invokable
 
Controller Middleware:
Request process:
User Request -> Middleware -> Controller -> Controller Method
E.g:
class UserController extends Controller
{
    public function __construct()
    {
        $ This-> middleware ( "auth"); // if not logged in will be redirected to the login route
        $ This-> middleware ( "log") -> only ( "test"); // perform only a method other than the current middleware index [can be an array] similar whitelist
        $ This-> middleware ( "subscribed") -> except ( "store"); // perform a method other than the current middleware Store [can be an array] similar blacklist
//        dd($this);
    }
 
    //
    public function show($id)
    {
        return view("user.profile",["user" => User::findOrNew($id)]);
    }
 
    // pubf + tab shortcut key generation method
    public function index()
    {
        echo "this is index()";
    }
 
    // whitelist method test ()
    public function test()
    {
 
    }
 
}
As the code reads the log file access log / the Users / XXXX / wwwn / test.laravel6.com/storage/logs
错误: Route [login] not defined.
The reason: When execution is not logged back Middleware \ Authenticate.php redirection method
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
 
            return route('login');
        }
    }
Error: Object type parameter log () expects parameter 1 to be float, object given
$ This-> middleware ( "log") This middleware error
 
Middleware can register by closure
Meanwhile, the controller also allows you to use a closure to register middleware. This definition is not the entire class of the middleware provides a convenient way to define a single controller middleware:
$this->middleware(function ($request, $next) {
    return $next($request);
});
 
Http request processing:
User Request -> Illuminate \ Http \ Request Class Request ->
Cookie laravel the post request carries CRSF token, if you want to post GET request mode may need to comment CRSF token verification in kernel.php follows:
    //  \App\Http\Middleware\VerifyCsrfToken::class,
public function store(Request $request, $name=null)
{
    $ Name = $ request-> input ( 'name'); // get either be acquired post request parameter
    $get = $request->get('name');
    $post = $request->post('name');
    $all = $request->all('name');
    dd($name,$get,$post,$all);
    return $name;
}
 
A route can both post parameters, but also where parameters get the address bar
Route::any("stores/{id}/{where?}","UserController@stores");
print:
"333"
"age"
array:2 [
  "u" => "getUser"
  "s" => "shengri"
]
 
Old data:
Laravel allows you to keep data between requests. This feature is especially useful when re-filling form after validity check error.
For example: Save username!
1.1 is stored in the session
    // read session data
    $ Name = $ request-> old ( "name"); // post mode request is stored in the session
    $ M = $ request-> old ( "m"); // where get mode request is stored in the session
    var_dump($name,$m);
    //dd($name,$m);
    Will write session request parameter file \ storage \ framework \ session \ .......
 
File: upload and download
php artisan make:controller FileController
Of course, you can also use the `hasFile` method to determine whether there is a file specified in the request:
if ($request->hasFile('photo')) {}
Upload verification is successful: In addition to checking whether the uploaded file exists, but you can also upload files to verify the validity of the method by `isValid`:
if ($request->file('photo')->isValid()) {}
File Path & extensions: `UploadedFile` class also contains the full path and method of access to the file extension. `Extension` method will determine the file name extensions based on file content. The extension and the extension may be provided by different clients:
$ Path = $ request-> photo-> path (); // temporary path
$ Extension = $ request-> photo-> extension (); // extension
 
Storing uploaded files:
To store the uploaded file, first configured [File System] ( https://learnku.com/docs/laravel/6.0/filesystem ). You can use the `store` method` UploadedFile` of the mobile upload files to one of your disk, the file may be a location on the local file system, even such as Amazon S3 cloud storage location.
`Store` path with respect to the method of receiving a file stored in the root directory of the file system configuration. This path must not include the file name, because the system will automatically generate a unique ID as the file name.
`Store` method also accepts an optional second parameter for the name of the disk to store files. This method returns the file path relative to the root directory of the disk:
$ Path = $ request-> photo-> store ( 'images'); // uploaded files saved in the default storage \ app \ images \ xxxxxx
$path = $request->photo->store('images', 's3');
If you do not want to automatically generate a file name, you can use `storeAs` method, which takes the path and file name of the disk name as its argument:
$path = $request->photo->storeAs('images', 'filename.jpg');
$path = $request->photo->storeAs('images', 'filename.jpg', 's3');
 
response:
Strings, arrays, view,
Response information can be customized for different response result, returns a response corresponding to the state
response string type text / html; charset = UTF-8
arr response type application / json
3.4.2 Response Object:
Usually, we do not simply return to action from routing strings and arrays, in most cases, will return a complete `Illuminate \ Http \ Response` instance or [view] ( https://learnku.com/docs/laravel /6.0/views ).
 
Examples of `return to the complete Response` allows you to customize the response status code and an HTTP response headers. Examples `Response` Inherited from` Symfony \ Component \ HttpFoundation \ Response` class, which provides various methods of constructing an HTTP response:
 
Route::get('home', function () {
    return response('Hello World', 200)
                  ->header('Content-Type', 'text/plain');
});
 
Add a response header:
Most of the response methods are available chained calls, making the process of creating a response examples more readable. For example, you can return in response to the user before use `header` method to add a bunch of headers:
return response($content)
            ->header('Content-Type', $type)
            ->header('X-Header-One', 'Header Value')
            ->header('X-Header-Two', 'Header Value');
Alternatively, you can use the `withHeaders` method to specify the header information to be added to the array of responses:
return response($content)
            ->withHeaders([
                'Content-Type' => $type,
                'X-Header-One' => 'Header Value',
                'X-Header-Two' => 'Header Value',
            ]);
 
Redirect:
Redirection response is an example of `Illuminate \ Http \ RedirectResponse` class, and contains the header information the user needs to be redirected to another URL required. Laravel provides several methods for generating `RedirectResponse` instance. The simplest method is to use a global auxiliary function `redirect`:
Route::get("home",function (){
    return redirect ( "string"); // redirect to a specified route
});
Route::get("home",function (){
    the redirect return ( " http://www.baidu.com");   // url redirected to an external connection
});
Route::get("cdx",function (){
    return redirect () -> away ( 'arr'); // redirected to the specified route
});
 
Sometimes you might want to redirect the user to the previous location, such as an invalid form submitted at the time. Then you can do this using a global helper functions `back`. Since this function takes advantage of [Session Control] ( https://learnku.com/docs/laravel/6.0/session ), be sure to route calls `back` function using` web` middleware middleware group or all Session:
Route::post('user/profile', function () {
    // verification request
    return back()->withInput();
});
 
Redirect to a named route:
If you call without auxiliary function parameters `redirect`, it will return` Illuminate \ Routing \ Redirector` instance. This example allows you to call any methods on `Redirector`. Generating for the named `RedirectResponse` e.g. routing,` route` method may be used:
return redirect()->route('login');
If there are routing parameters can be passed as parameter to `route` second method:
return redirect()->route('profile', ['id' => 1]);
 
Redirected to the controller action:
You may also be generated to [Action Controller] ( https://learnku.com/docs/laravel/6.0/controllers ) redirection. To achieve this object, `action` method as long as the name of the controller and transmitted to the action. Remember, do not need to pass all of the namespace controller, Laravel of `RouteServiceProvider` will automatically be set to the namespace basic controller:
return redirect()->action('HomeController@index');
If the controller requires the routing parameters, it can be used as a method `action` second argument:
return redirect()->action(
    'UserController@profile', ['id' => 1]
);
Redirected to the external domain name:
Sometimes you need to redirect the domain name to the external application. Call `away` ways to achieve this, it will create a URL without any additional coding,` RedirectResponse` examples validity checking and inspection:
return redirect()->away(' https://www.google.com');
Other types of responses:
`response` assistant may be used to generate examples of other types of response. When you call `also arguments response` assistant, Illuminate return` \ Contracts \ Routing \ ResponseFactory` [Contract] ( https://learnku.com/docs/laravel/6.0/contracts ) of a realization. The contract number is provided a method for generating a response:
View response:
If you need to [view] ( https://learnku.com/docs/laravel/6.0/views ) as a simultaneous return of the response content, and state control response header information, you need to call `view` method, if no transfer from defined custom HTTP status codes and header information, you may also be used globally `view` helper.
return response()
            ->view('hello', $data, 200)
            ->header('Content-Type', $type);
JSON response:
`Json` automatically` Content-Type` header set to `application / json`, while using the` json_encode` PHP function given array to a JSON:
return response()->json([
    'name' => 'Abigail',
    'state' => 'CA'
]);
If you want to create a JSONP response, it can be combined with `withCallback` method uses the` json` method:
return response()
            ->json(['name' => 'Abigail', 'state' => 'CA'])
            ->withCallback($request->input('callback'));
 
document dowload:
1. Set http response header
2. Download the file name, size,
return response()->download($pathToFile);
return response()->download($pathToFile, $name, $headers);
return response()->download($pathToFile)->deleteFileAfterSend();
 
RESTful style: Definition:
REST is an acronym for "showing state transition (REpresentational State Transfer)" is. Perhaps it can be to define it: one API's architectural style, between the client and server applications to drive the evolution of the state by transferring presence state.
 
constraint:
Let RESTful applications, it is necessary to follow the following constraints. Follow these constraints distributed systems, we will have the following non-functional attributes: performance, scalability, ease of use, scalability, visibility, portability and reliability.
 
CS mode:
CS mode by separating concerns the client and server side, so that the client no longer concerned with the problem of data storage, thereby increasing the portability of client-side code. On the other hand, the server is no longer concerned about the user interface and user status, so that it becomes easier to improve the scalability. Server-side with clients can be developed independently, as long as they comply with the contract.
 
no status:
In the context of the client across multiple requests are never stored on the server. Each request must contain the necessary information. Stateless server resources by quickly releasing and simplify the implementation of improved scalability. So that reliability from the local failure can be easily restored. Obviously, the monitoring system is not necessary to determine the nature of the request by considering a single request. One drawback stateless server network performance is reduced, because all the necessary data must be sent in every request.
 
Cacheable:
REST system is a web application, the client may cache the response and the intermediate layer. Response must be defined as cacheable or non-cacheable to prevent reuse of the old client data reliability is degraded. If stale data in the cache data request generated significantly different, by the server processes the request. Cache can eliminate some of the interaction between the client and the server, which improves scalability, efficiency and by reducing the average delay to reach the user-perceptible performance.
 
Unified interface:
Use unified interface reduces system complexity and coupling, so that different parts of the system can be independent evolution. I will explain later URI, hypermedia resources and how to improve user interaction by generating a standard interface visibility, reduce system complexity, promote system components independent evolution. But we need to make compromises in terms of efficiency, after all, the message is transmitted via a standard format, and can not meet all the requirements of the application message formats.
 
Tiered system:
Layered systems reduce system complexity by constraining the behavior of the component, the component can not pass them to the media access layer of the other layers. To maintain independence between the assembly by blocking layer. Remaining components may be packaged into a new layer, to prevent the old client access. Medium layer may be scalability through load balancing hoist. The main shortcomings of the hierarchical system, it gives the data processing adds some additional overhead, increased latency, have an impact on the user experience.
 
Demand Code:
 
REST allows the client to expand their capabilities, simplifies the client by downloading execute the script, but also enhance scalability. But it also reduces visibility, so this constraint is not mandatory.
 
element:
REST provides the following elements to construct stateless, scalable web API.
 
HTTP protocol:
Resources
HATE
Hypermedia
HTTP - HyperText Transfer Protocol
 
REST typically using HTTP as its transport protocol, since HTTP provides some good use characteristics, such as HTTP verbs, status codes and header information
 
HTTP verbs:
HTTP does not define many verbs to describe the behavior of web services that may appear, it only took a standard set of verbs to deal with similar situations, so that the API more intuitive. Each verb to meet the needs of different scenarios by a combination of two attributes.
 
Idempotent: operation may be repeatedly performed even after the failure.
Security: for the client operation does not cause side effects.
 
GET:
Used to read status from the server. This operation is safe, so it can be executed many times without any impact on data, which means that once it is executed with the implementation of ten times the same effect. From the point of view in terms of power and the like, many requests with a single request can always get the same results.
 
POST:
Generally used to create a certain state on the server side. This operation does not have idempotency with security, so many requests will create more resources on the server side. Because POST is not idempotent, so should not be used to make a relationship with money operations, imagine if a failed request to be executed multiple times, then it may transfer or pay also performed several times.
 
PUT:
Although it can also be used to create a state, but mainly used in server-side update status. It is idempotent, but insecure, because it will change the state of the server. Because of its idempotency, PUT can be used to handle a relationship with money operation.
 
DELETE:
To delete the state on the server side. It is also the power of other non-secure, because it would remove the state of the server. The reason it is idempotent, because a state-duplication result is the same.
 
Response status code:
HTTP provides metadata information in response to the resource request, the status code is. They are an important factor in web platform has been able to build distributed systems. They are divided into the following categories:
- 1xx - Metadata
- 2xx - the correct response
- 3xx - Redirection
- 4xx - Client Error
- 5xx - server error
 
Header information:
In the HTTP message header that provides additional information in response to requests. Each head of the case-sensitive keywords and values, separated by a colon. Header information is divided into the following categories:
General head: has, in the message body with the data transmission request with no relationship in response.
Request header: More information about the requested resource or client.
Response headers: Additional information about the response.
Entity header: Additional information message bodies, such as content-length or MIMI-type.
 
Resources:
Resources can be anything with a unique identity exposed by the system. Resources between applications with the client to establish a connection. A picture, a table, or a collection of them, are considered resources. Resources are acquired or created (XML, JSON, etc.) by some kind of presentation. We are dealing with is presented in the form of resources, not the resource itself, a bit like this passed with value. According to the previous definition of REST resources on behalf of the documents transmitted over the network. Concerned about the state of the server-side resources, because they represent the state of the field. The client simply gets sent or present state resources, so that the state of the application changes. Customer care is the single state of the application, because these state changes with the target application to be achieved are related. The name of the resource should be the nature of the term, they represent a conceptual system in the field, and identified by a URI.
 
URIs  (Uniform Resource Identifiers)
URIs used to uniquely identify resources. To access a resource or operating, at least to know the address of the resource. They are composed of server address + path + protocol.
The client should not have too many resources and URI coupling, because the server may randomly change their values. At this point, hypermedia advantage. It provides a way to decouple the client with the URI and add new semantics in application protocols.
 
Resource Controller:
Summary:
Laravel routing resources of the typical "CURD (CRUD)" routing assigned to the controller with a single line of code. For example, you want to create a controller to handle Save "Photos" application of all HTTP requests. Using Artisan command `make: controller`, we can quickly create a controller like this:
php artisan make:controller PhotoController --resource
This command will generate a controller `app / Http / Controllers / PhotoController.php`. Wherein each method comprises the operation of available resources.
 
Next, you can register a resource route to the controller:
Route::resource('photos', 'PhotoController');
 
This single routing declaration creates multiple routes to deal with various acts of resources. The controller maintains a generating method of each behavior, including comments on the declaration process of HTTP verbs and URLs.
 
You can pass an array by reference to `resource` method way to create multiple one-time Resource Controller:
Route::resources([
    'photos' => 'PhotoController',
    'posts' => 'PostController'
]);
 
Resource Controller operation process:
 
| HTTP method | URI | action | Route Name |
| --------- | ---------------------- | ------- | -------------- |
| GET       | `/photos`              | index   | photos.index   |
| GET       | `/photos/create`       | create  | photos.create  |
| POST      | `/photos`              | store   | photos.store   |
| GET       | `/photos/{photo}`      | show    | photos.show    |
| GET       | `/photos/{photo}/edit` | edit    | photos.edit    |
| PUT/PATCH | `/photos/{photo}`      | update  | photos.update  |
| DELETE    | `/photos/{photo}`      | destroy | photos.destroy |
 
Develop resource model:
If you use a routing model binding, and want to use the type of prompt in the method of resource controller, you can use the `--model` options when generating controller:
php artisan make:controller PhotoController --resource --model=Photo
 
 
Some resources route:
Route::resource('photos', 'PhotoController')->only([
    'index', 'show'
]);
Route::resource('photos', 'PhotoController')->except([
    'create', 'store', 'update', 'destroy'
]);
 
API routing resources:
When the resource statement for routing APIs, usually need to exclude route display HTML templates (such as `create` and` edit`). For convenience, you can use apiResource method to automatically exclude these two routes:
 
Road :: apiResource ( 'pictures', 'PhotoController');
 
You can pass an array to the `apiResources` method to simultaneously register multiple API Resource Controller:
Road :: apiResources ([
    'photos' => 'PhotoController',
    'posts' => 'PostController'
]);
 
To quickly create` or which does not include `` resource controller for interface development edit` methods, performing the make `:` --api` using controller` command switch:
php artisan make:controller API/PhotoController --api
 
Named routing resources:
By default, all routing resource controller behavior has a name. You can pass an array of names to cover these names:
Route::resource('photos', 'PhotoController')->names([
    'create' => 'photos.build'
]);
Named resource routing parameters:
 
By default, `Route :: resource` routing resources will create a routing parameters according to" singular "form of resource names. You can pass parameters in `parameters` option to easily cover an array for each resource. `Parameters` array should be an associative array of resource names and parameter names
Route::resource('users', 'AdminUserController')->parameters([
    'users' => 'admin_user'
]);
 
The above example will generate the following URI is `show` routing resources:
/users/{admin_user}
 
php artisan make:controller Api/ResController --resource
php artisan route:list
 
 
 
 

Guess you like

Origin www.cnblogs.com/dreamofprovence/p/11784855.html