简体   繁体   中英

Concaternate Array value with Ternary Operator result

I'm using PHP 7 and Laravel 6. I got errors when I made a user request rule and used it in user controller. The request rule I made is to be reusable in create and update function, so if i pass the id of user, it will validate the unique of user except that id. But if not, it will search all the ids and validate if it's unique. I follow BaM solution, here: https://stackoverflow.com/a/24205849

This my UserRequest.php:

public static function rules ($id=0, $merge=[]) {
    return array_merge(
        [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users' . ($id ? ",$id" : ''),
            'phone_number' => 'required|string|min:9|max:10|unique:users' . ($id ? ",$id" : ''),
            'user_img' => 'required|mimes:jpeg,jpg,png,gif|max:10000',
        ], 
            $merge);
}

This is my UserController:


public function store(Request $request)
  {
    $extend_rules = [
      'pass'       => 'required|string|min:8',
  ];

    $validator = Validator::make($request->all(), UserRequest::rules($extend_rules));

    if ($validator->fails())
    {
      return redirect()->back();
    }

    $user = User::create([
      'name' => $request->name,
      'email' => $request->email,
      'password' => Hash::make($request->pass),
      'phone_number' => $request->phone_number,
      'user_img' => $request->user_image->store('user_img'),
    ]);

    $user->save();

    Session::flash('message', 'Your account is successfully created !');
    Session::flash('alert-class', 'alert alert-success');
    

    return redirect()->route('users.index');
    
  }

And I got this errors:

ErrorException: Array to string conversion

I tried to search for solutions but couldn't seem to find anything much my case.

If anyone know, please help me!

That's because you're just passing an array while the method accept two different type of parameter

$validator = Validator::make($request->all(), UserRequest::rules(0, $extend_rules)); // <-- you need to either pass 1 or 0 for the id and then $extended rules

// here is your method signature
public static function rules ($id=0, $merge=[]) {

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