У меня возникла ошибка. Попытка прочитать свойство «id» в нулевом Laravel 8 при попытке показать мою таблицу.
Таблицы миграции< /strong>
Код: Выделить всё
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('username', 20)->unique();
$table->string('password', 20);
$table->enum('level',['admin', 'manager', 'pegawai']);
$table->timestamps();
});
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->foreignId('id_user')
->constrained('users')
->onUpdate('cascade')
->onDelete('cascade');
$table->string('nama_pgw', 50);
$table->string('alamat');
$table->string('no_telp', 13);
$table->string('email', 30)->unique;
$table->timestamps();
});
Код: Выделить всё
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
use HasFactory;
protected $table = 'employees';
protected $fillable = ['nama_pgw', 'username', 'alamat', 'no_telp', 'email'];
public function user(){
return $this->hasOne(User::class);
}
}
Код: Выделить всё
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use HasFactory;
protected $table = 'users';
protected $fillable = ['username', 'password', 'level'];
public function employee(){
return $this->belongsTo(Employee::class, 'id_user', 'id');
}
}
Код: Выделить всё
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\User;
class UserController extends Controller
{
public function index()
{
$users = User::get();
return view('user/index', compact('users'));
}
}
Код: Выделить всё
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Employee;
use App\Models\User;
class PegawaiController extends Controller
{
public function index()
{
$pegawai = Employee::get();
return view('pegawai/index', compact('pegawai'));
}
}
Код: Выделить всё
- pilih username -
@foreach ($pegawai as $emp)
option value="{{$emp->users->id}}">{{$emp->users->nama_pgw}}
@endforeach
спасибо!
Подробнее здесь: https://stackoverflow.com/questions/668 ... -laravel-8
Мобильная версия