Ihsan
Ihsan

Reputation: 35

json response with 2 table in Laravel 5.6

why my code get error

  public function AuditorBagian_Edit($nopek)
  {

    $user = User::where('nopek', '=', $nopek)->get();
    $bagian_user = Bagian::all()->where('kode_bagian', '=', $user->bagian)->get();

    return response()->json($bagian_user);

  }

I want to show data from Bagian

Upvotes: 1

Views: 815

Answers (3)

Kurt Chun
Kurt Chun

Reputation: 421

Just remove the ::all() will do, all() and get() is the same behaviour.

Take not that all(), get(), first() is the final step to get the model data, the condition and with() and ordering() and etc must happen before all the three above mentioned

Upvotes: 0

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

Error result of code

$bagian_user = Bagian::all()->where('kode_bagian', '=', $user->bagian)->get();

Bagian::all() return instance of Illuminate\Database\Eloquent\Collection and find all records in db, then you try to filter ->where('kode_bagian', '=', $user->bagian)->get() specific records but this code wrong because method where() of Illuminate\Database\Eloquent\Collection class return instance of Illuminate\Database\Eloquent\Collection and this class does not haveget() method.

User::where('nopek', '=', $nopek)->get() also return instance of Illuminate\Database\Eloquent\Collection. To get single record use first() method instead of get()

The correct way get result is

$user = User::where('nopek', '=', $nopek)->first();

if(!empthy($user)) {
    $bagian_user = Bagian::where('kode_bagian', '=', $user->bagian)->get().
}

Edited, format php code

Upvotes: 1

Hamelraj
Hamelraj

Reputation: 4826

You can pass collection or array into response()->json() function it will convert as JSON data

 public function AuditorBagian_Edit($nopek)
          {

            $user = User::where('nopek', '=', $nopek)->get();
            $bagian_user = Bagian::where('kode_bagian', '=', $user->bagian)->get();
    // or $bagian_user = Bagian::where('kode_bagian', '=', $user->bagian)->get()->toArray();

            return response()->json($bagian_user);

          }

Upvotes: 1

Related Questions