Как использовать данные из базы данных в моем контроллере в Laravel, используя Eloquent - PullRequest
0 голосов
/ 12 января 2019

Я пытаюсь получить имя, фамилию и курс из базы данных. Моя модель называется Youth.

    $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 голосов
/ 12 января 2019

Многократный запрос вашей модели Youth с одним и тем же id не требуется. Вы делаете три запроса, когда одного будет достаточно.

Вот что должно работать.

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');
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...