我如何使用雄辩的方法在laravel的控制器中使用数据库中的数据

时间:2019-01-12 11:10:57

标签: eloquent laravel-5.4

我正在尝试从数据库中获取名字,名字和课程。我的模特叫青春。

    $id = auth()->user()->id;

    $firstname = Youth::where('id', $id)->get(['firstname']); 
    $secondname = Youth::where('id', $id)->get(['secondname']);   
    $course = Youth::where('id', $id)->get(['course']);

然后使用在我的称为通知的字符串中提取的数据,该数据将存储在我的通知表中。

     $notification = 'Internship application by ' . $firstname . $secondname . ' from ' . $start_date . ' to ' . $end_date . ' in ' . $course;    

    auth()->user()->notify(new Internship($notification));

执行此操作时,从数据库获取的字符串为空。这是我完整的代码和结果。

public function InternshipSearch(Request $request)
{
    $this->validate($request,[
        'start_date' => 'required',
        'end_date' => 'required'
    ]);

    $start_date = $request->input('start_date');
    $end_date = $request->input('end_date');


     $id = auth()->user()->id;

    $firstname = Youth::where('id', $id)->get(['firstname']); 
    $secondname = Youth::where('id', $id)->get(['secondname']);   
    $course = Youth::where('id', $id)->get(['course']);

     $notification = 'Internship application by ' . $firstname . $secondname . ' from ' . $start_date . ' to ' . $end_date . ' in ' . $course;    

    auth()->user()->notify(new Internship($notification));

    //return back()->with('success','Internship application sent');
    return $notification;


}

我得到以下结果:

  

[]在[]中于2019-01-08至2019-01-17进行实习申请

青年模特

    class Youth extends Model
{
    protected $table ='youth';
    public $primaryKey='id';
    public function user(){
        return $this->BelongsTo('App\User');
    }
}

1 个答案:

答案 0 :(得分:0)

不需要多次使用相同的id查询Youth模型。当一个查询就足够时,您要进行三个查询。

这是应该起作用的。

public function InternshipSearch(Request $request)
{
    $this->validate($request,[
        'start_date' => 'required',
        'end_date' => 'required'
    ]);

    $user  = auth()->user();
    $youth = Youth::where('id', $user->id)->first();

    if(! $youth) { 
        return back()->with('error', 'Record not found');
    }

    $notification = sprintf(
        'Internship application by %s %s from %s to %s in %s',
        $youth->firstname,
        $youth->secondname,
        $request->input('start_date'),
        $request->input('end_date'),
        $youth->course
    );

    $user->notify(new Internship($notification));

    return back()->with('success','Internship application sent');
}