Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hafiz_r's avatar

Show data assigned to the foreign key.

I have an appointment table with id, counselor_id(fkey), student_id(fkey). so how can i show the students info assigned with the counselor_id when the counselor logs in as user?

I just need to know how can i write the controller.

    $user = Auth::user();
    $appointment = Appointment::get();
    if ($user->id == $appointment->counselor_id) {
        $students = $appointment->student_id;
        return view('appointedStudents')->with('appointedStudents', $students);
   

Thanks

0 likes
14 replies
ismaile's avatar

In the Controller, you should have something like this:

$students = Auth::user()->students()->get();
 return view('appointedStudents')->with('appointedStudents', $students);

And in User.php, inside the User class, something like this:

public function students()
    {
        return $this->belongsToMany('App\Student', 'appointments', 'counselor_id', 'student_id');
    }

Here I assume your DB table is called appointments, and you have a model called Student

1 like
rodrigo.pedra's avatar

You can add a where constraint when fetching the appointments:

$user = Auth::user();

$appointments = Appointment::query()
    ->with(['student']) // eager load appointment's student
    ->where('counselor_id', $user->id) // filter by current user
    ->get();

$students = $appointments
        ->pluck('student')
        ->unique('id');

return view('appointedStudents')->with('appointedStudents', $students);
rodrigo.pedra's avatar

@ismaile solution seems a better one as you don't need to change the collection result. Also as Appointment contains both keys it can be thought as a pivot table between Counselor and Student.

Didn't see before posting mine.

1 like
rodrigo.pedra's avatar

Can you post the error stack trace?

Also are your models inside the /app folder? Or are they in a different namespace?

hafiz_r's avatar

Call to undefined relationship [student_id] on model [App\Appointment]. error for yours solution

models are in app

hafiz_r's avatar

@extend('layouts.app') @section('content') @if (count($students)>0) @foreach ($students as $student)

    <li class="list-group-item">Name: {{$student->name}}</li>
    <li class="list-group-item">Email: {{$student->email}}</li>
    <li class="list-group-item">Counselor Type: {{$student->matric}}</li>
    
@endforeach @endif @endsection

DB

$table->increments('id'); $table->integer('student_id')->unsigned()->nullable(); $table->foreign('student_id', '35989_5913ebf64ed0b')->references('id')->on('students')->onDelete('cascade'); $table->integer('counselor_id')->unsigned()->nullable(); $table->foreign('counselor_id', '35989_5913ebf652b9b')->references('id')->on('counselors')->onDelete('cascade'); $table->datetime('date')->nullable(); $table->text('comments')->nullable(); $table->timestamps();

[2019-11-19 07:03:20] local.ERROR: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it. (SQL: select * from students where email = [email protected] limit 1) {"exception":"[object] (Illuminate\Database\QueryException(code: 2002): SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it. (SQL: select * from students where email = [email protected] limit 1) at C:\Users\Hafiz\Desktop\Learning\Laravel\fyp\ecounseling\vendor\laravel\framework\src\Illuminate\Database\Connection.php:665) [stacktrace]

rodrigo.pedra's avatar

The last error you posted is related to the Database connection.

Can you post the Appointment model.

I assumed relations were defined as usual:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Appointment extends Model
{
  public function counselor() {
    return $this->belongsTo(User::class, 'counselor_id');
  }

  public function student() {
    return $this->belongsTo(Student::class);
  }
}

Where the Appointment, 'User and Student class are located in the /app directory.

If everything looks like above the pluck method might be converting the student models to plain arrays, so you could replace it for the map method:

$students = $appointments
        ->map(function ($appointment) {
           return $appointment->student;
        })
        ->unique('id');
hafiz_r's avatar

Undefined variable: students

are we making all the syntax right?

rodrigo.pedra's avatar
Level 56

On your view you reference a $students variable, but from your controller you send a $appointedStudents variable.

Change that in your blade file.

EDIT: or in your controller:

return view('appointedStudents')->with('students', $students);
hafiz_r's avatar

it worked. sorry i forgot to mention how can i return a column date from the appointment table with this user?

and how can i implement destroy here?

Thanks a lot So much grateful to you

1 like
rodrigo.pedra's avatar

The ->with(...) after the view(...) is how er pass variables from the controller to view.

return view('appointedStudents')->with('students', $students);

This method allows you to use a different name for that variable in your view. So if you kept as before you would have to change your view to:

@if (count($appointedStudents)>0) @foreach ($appointedStudents as $student) ...

As before the last change you were renaming the $students variable in the controller to $appointedStudents in the view through the ->with(...) method.

What do you want to destroy? Every appointment with a student? or a student record?

Unfortunately, right now I don't have the time, my suggestion is you to open a new issue in the "Assistance" category.

But basically the outline will be the following:

1. Add a delete route mapped to dedicated controller method

// routes/web.php

Route::delete('/appointments/student/{student}', 'AppointmentsController@destroy');

2. Add the destroy controller method to the AppointmentsController

public function destroy(Student $student) {
  $user = Auth::user();

  Appointment::query()
    ->where('counselor_id', $user->id) // filter by current user
    ->where('student_id', $student->id)
    ->delete();

  return back();
}

If your Student model is named like that Laravel will automatically fetch the related instance by its primary key

3. in your blade for each interaction add a form with a remove button:

<li class="list-group-item">Name: {{$student->name}}</li>
<li class="list-group-item">Email: {{$student->email}}</li>
<li class="list-group-item">Counselor Type: {{$student->matric}}</li>
<li class="list-group-item">
  <form method="POST" action="/appointments/student/{{ $student->id }}" 
    class="d-inline-block"
    onsubmit="return confirm('Are you sure?')">
    @csrf @method('DELETE')
    <button type="submit" class="btn btn-danger">
      remove
    </button>
  </form>
</li>
</li>
hafiz_r's avatar

I got the whole idea.

Only one thing left is to get the date from appointment table for that student.

If you have time reply if not ignore it.

But i really appreciate your help.

rodrigo.pedra's avatar

So you should send the appointments not the students...

In your controller:

$user = Auth::user();

$appointments = Appointment::query()
    ->with(['student']) // eager load appointment's student
    ->where('counselor_id', $user->id) // filter by current user
    ->whereHas('student') // only appointments with students
    ->get();

return view('appointedStudents')->with('appointments', $appointments);

I added the ->whereHas(...) condition so only appointments with students are retrieved.

As in your DB schema the student_id column is nullable, the table currently allows an appointment without a student to be saved. If your app prevents that feel free to remove this condition

In your view:

@extend('layouts.app')

@section('content')

<ul class="list-group">
  @forelse ($appointments as $appointment)
    <li class="list-group-item">
      Name: {{ $appointment->student->name }}
    </li>
    <li class="list-group-item">
      Email: {{ $appointment->student->email }}
    </li>
    <li class="list-group-item">
      Counselor Type: {{ $appointment->student->matric }}
    </li>
    <li class="list-group-item">
      Date/Time: {{ optional($appointment->date)->format('Y-m-d H:i:s') }}
    </li>
    <li class="list-group-item">
      <form method="POST" action="/appointments/{{ $appointment->id }}" 
        class="d-inline-block"
        onsubmit="return confirm('Are you sure?')">
        @csrf @method('DELETE')
        <button type="submit" class="btn btn-danger">
          remove
        </button>
      </form>
    </li>
  @empty
    <li class="list-group-item">
      <em class="text-muted">No appointments</em>
    </li>
  @endforelse
</ul>

@endsection

Change the DELETE route to:

// routes/web.php

Route::delete('/appointments/{appointment}', 'AppointmentsController@destroy');

And the destroy method on the AppointmentsController will be simply be:

public function (Appointment $appointment)
{
  $appointment->delete();

  return back();
}

Please or to participate in this conversation.