我正在使用Laravel6。我正在尝试使用表单创建会议的验证系统。 当用户与已经被另一个会议占用的参与者创建会议时,视图中应显示一条消息,其中已被占用的参与者的名称。 由于某种原因,应该找到参与者名称的功能无法正常工作。我在foreach循环中传递了一个id,但运行表单时出现以下消息:“试图获取非对象的属性'name'”。 奇怪的是,传递给该函数的id可以,但是如果我在查询中正确地在查询中以$ id代替$ id的形式写了一个数字(例如“ 8”),则该名称正确显示为“ Chris”。 表会议中“ id_participants”列的格式为以下“ 23; 7; 6”。
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use DB;
use App\User;
class CheckParticipant implements Rule
{
protected $participants_occupied = array();
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute,$value)
{
$participants = request('participants');
foreach($participants as $participant) {
$meetings = DB::table('meetings')
->where('is_active','1')
->where('date',request('date_meeting'))
->where(function ($query) {
$query->where(function($sub_q) {
$sub_q->where('start_hour','>=',request('start'))
->where('start_hour','<',request('end'));
})
->orWhere(function($sub_q) {
$sub_q->where('start_hour',request('start'))
->where('end_hour',request('end'));
})
->orWhere(function($sub_q) {
$sub_q->where('end_hour','>','<=',request('end'));
});
})
->where(function ($query) use($participant) {
$query->where('id_participants',$participant)
->orWhere('id_participants','like','%;'.$participant)
->orWhere('id_participants',$participant.';%')
->orWhere('id_participants','%;'.$participant.';%');
})
->get();
if(count($meetings) > 0) {
array_push($this->participants_occupied,$participant);
}
}
if(count($this->participants_occupied) > 0) {
return false;
} else {
return true;
}
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
for($i = 0; $i < count($this->participants_occupied); $i++) {
$this->participants_occupied[$i] = $this->getNameSurnameById($this->participants_occupied[$i]);
}
return 'The participants are already occupied at that time: ' . implode(',',$this->participants_occupied);
}
public function getNameSurnameById($id)
{
$users = User::all()->where('id',18)->first(); //if I write a number in place of $id everything works
return $users->name;
}
}
我希望该程序可以动态运行。我想在查询中变量$ id有问题。有人可以帮助我吗?
更新:
我解决了如下修改消息功能的问题:
public function message() { $arr_names = array(); //I created this array for($i = 0; $i < count($this->participants_occupied); $i++) { array_push($arr_names,$this->getNameSurnameById($this->participants_occupied[$i])); } return 'The following participants are already occupied at that time: ' . implode(',$arr_names); }
我认为问题在于,我给具有整数值(参与者的id)的数组提供了一个字符串值(参与者的名称)。我解决了创建一个新的空数组的问题,并将名称推到了新数组中。