Laravel Advanced Task Notes

Source: Internet
Author: User

At the beginning of the task, we will expand the New database table migration file. The newly created migration file has only two columns and is manually added as follows:

 Public function Up ()    {        Schemafunction$table) {            $table->increments (' id ');             $table,integer(' user_id '),index ();             $table,string(' name ');             $table-timestamps ();        });    

Use the command again to build the table:

PHP Artisan Migrate

Create Model:

make: Model Task

This time we will add a property to the new model:

<? phpnamespace App;  Use Illuminate\database\eloquent\model; class extends model{    /* * * The attributes that is     mass assignable.     *     * @var array     */    protected$fillable = [' name '];}

With Fillable, we declare that the Name property is mass-assignable. The current understanding of mass-assignable means that different types of assignments are allowed.

After the definition of models, we now need to declare their relationship.

Define the relationship to the task in User:

class extends authenticatable{    // other eloquent Properties    ... /* *     Get      All of the tasks for the user. */     Public function tasks ()    {        return$this->hasmany (Task::class);    }}

Define the relationship with user in the task:

 extends   model{ /*  * * The attributes that is MA     SS Assignable. * * @var array  */ protected   $fillable  = [' name '  /*  * * Get the user that owns the task.  */ public  function   user () { return   $this ->belongsto (user::class  ); }}

Now we use the controller to organize our router. Because user authentication is a common feature, this feature is already integrated in Laravel. The command is as follows:

make: Auth--views

After that, add the following line to the router:

Route::auth ();
protected $redirectTo = ‘/tasks‘;

This will automatically register the user authorization and redirect the illegal user to/tasks.

We also need to define redirects in the middleware app/Middleware/RedirectIfAuthenticated.php :

Return Redirect ('/tasks');

In the advanced task, we use the controller to design the business logic. The artisan syntax for creating a Taskcontroller under Directory app/http/controllers is as follows:

make: Controller Taskcontroller

Once the controller is created, the business logic in the controller can be mapped in router according to the URL:

Route::get ('/tasks ', ' [email protected] '); Route::p ost ('/task ', ' [email protected] '); Route::d elete ('/task/{task} ', ' [email protected] ');

With the controller, we can easily use the middleware for all controllers in the business of user Rights Management, just to add in the Taskcontroller you just created:

class extends controller{    /* * *     Create a new Controller instance.     *     * @return void     */public    function  __construct ()    {         $this->middleware (' auth ');}    }

The method of defining the view is consistent with the basic task, except that the path to the partial file store is different, after which we can define our business logic in the controller:

 Public function $request {    return view (' Tasks.index ');}

The method for storing the task is the same as in the basic task, except that it needs to be defined in the controller.

 Public function $request {    $this->validate ($request, [        ' name ' = ' = ' required| max:255 ',    ]);
$request->User()->Tasks()->Create([ ' name ' => $request->name, ]); return redirect('/tasks ');          
}

It can be found that the validation at the time of storage differs from the router in our basic tasks. Because the controller class natively supports validate, the errors variable is automatically pressed into the session after validation fails and redirected to the pre-access page.

When creating a task, we can use the relationship between user and task, through which we can automatically set the UserID for the task.

At this time, our main page also need to join the function of the display task, the code is as follows:

 Public function $request ) {    $tasks$request->user ()->id),get ();     return view (' Tasks.index ', [        $tasks,    ]);}

Here, the task is obtained by the where query, and the tasks are passed to Tasks.index

However, the logic of the data also needs to be managed by defining taskrepository in the task model. Because model is a collection of operations for a particular table. We may have different operations on the table for different business logic, so we should register all operations for ease of reuse.

We create a new repositories directory under the app directory and created the Taskrepository class:

namespace App\repositories; UseApp\user; UseApp\task;classtaskrepository{/** Get All of the tasks for a given user. * * @param User $user * @return Collection*/     Public functionForuser (User$user)    {        returnTask::where (' user_id ',$user-ID)->orderby (' Created_at ', ' ASC ')                    -get (); }}

Next we need to introduce repository to our controller:

namespace App\http\controllers; UseApp\task; Useapp\http\requests; Useilluminate\http\request; UseApp\http\controllers\controller; Useapp\repositories\taskrepository;classTaskcontrollerextendscontroller{/** * The task repository instance. * * @var taskrepository*/    protected $tasks; /** * Create a new controller instance. * * @param taskrepository $tasks * @return void*/     Public function__construct (taskrepository$tasks)    {        $this->middleware (' auth '); $this->tasks =$tasks; }    /** Display A list of all of the the user's task. * * @param Request $request * @return Response*/     Public functionIndex (Request$request)    {        returnView (' Tasks.index ', [            ' Tasks ' =$this->tasks->foruser ($request->user ()),        ]); }}

The view and basic tasks of data presentation and deletion are consistent and not duplicated.

The next step is to distinguish it from the basic task, where we use the Destroy method: router

Route::d elete ('/task/{task} ', ' [email protected] '); /* * * Destroy the given task. * * @param  Request  $request * @param  Task  */publicfunction$request $task ){    //}

Above is the router file, the following is the corresponding method in the controller file. You can see that there is an implicit argument, and {task} is automatically passed to the $task variable.

Since we introduced the user privilege mechanism, we are concerned that the user is free to pass task_id during the deletion process, so we need to establish a policy to prevent this situation. Policy can integrate authorization logic into the process. Usually a policy corresponds to a model. We created the app/policies/taskpolicy. php files via artisan:

make:p olicy taskpolicy

We need to declare the permissions required for a method in Taskpolicy. In this case, the Destroy method needs to confirm whether the user's taskid and this taskid correspond:

<? phpnamespace app\policies;use app\user;use app\task;use illuminate\auth\access\handlesauthorization;class taskpolicy{use    handlesauthorization;     /* *     * Determine if the given user can delete the given task.     *     * @param  User  $user     * @param  Task  $task     * @return bool     */ function Destroy (User $user, Task $task)    {        return $user        ID = = = $taskuser_id;    }}

Then we need to associate the task model with the Taskpolicy and declare it in the$policies variable of the file app/providers/authserviceprovider. PHP:

/**/protected$policies =    [' app\task ' = ' app\policies\ Taskpolicy ',];

This allows all tasks to be delegated to taskpolicy.

Now back to our controller:

 Public function $request $task ) {    $this$task);
  $task->delete(); return redirect(‘/tasks‘);
}

The current user is automatically routed, so no additional delivery is required. If the authorization fails, it will jump to page 403.

Laravel Advanced Task Notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.