简体   繁体   中英

Laravel Eloquent Model Dependency Injection with preformated Id to find()

Normally we can simplify finding User by id logic in controller by injecting the User Class in parameter. Like this:

class UserController extends Controller
{
   public function show(User $id)
   {
      return $user;
   }
}

But now I must treat the Id to find like this:

<?php
namespace App\Http\Controllers;

class UserController extends Controller
{
   public function show(User $id)
   {
      $preformattedId = '98'.$id;

      $user = User::find($preformattedId );

      return $user;
   }
}

My basic question is: how I can achieved that same trick to my preformatted id in below code like the above code?

Note: I have to use the Id this way because i work with legacy database that actually adding that '98' prefix in every Id, despite that we only use characters after that prefix.

You can use Inversion of Control by using explicit binding on your router.

In your RouteServiceProvider

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    parent::boot();

    Route::bind('user', function ($value) {
        return User::find('98'.$value);
    });
}

Or in your User model

/**
 * Retrieve the model for a bound value.
 *
 * @param  mixed  $value
 * @param  string|null  $field
 * @return \Illuminate\Database\Eloquent\Model|null
 */
public function resolveRouteBinding($value, $field = null)
{
    return $this->find('98'.$value);
}

https://laravel.com/docs/7.x/routing#explicit-binding

You can share your route file?

But if your file is

Route::get('user/{id}', 'UserController@show');

When you use

class UserController extends Controller
{
   public function show(User $id)
   {
      // you don't need use find function, it is make automatic by laravel
      $user = $id;
      return $user;
   }
}

if you want to get id, just remove User type inside show parameter

class UserController extends Controller
{
   public function show($id)
   {
      $preformattedId = '98'.$id;

      $user = User::find($preformattedId );

      return $user;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM