Fetch data from another table to select in laravel 5.5 - laravel

I got a problem when I try to fetch data from table to select.
here is my Mahasiswa model :
protected $fillable = ['nim','nama','alamat','jenis_kelamin','no_tlp','email','tempat','tanggal','link','id_jurusan'];
protected $table = 'mahasiswa';
public function jurusan(){
return $this->belongsTo('App\Jurusan');
}
here is my MahasiswaController :
public function create()
{
$data['data']= Mahasiswa::with('jurusan')->get();
return view('Mahasiswa.mahasiswaInsert',$data);
}
and here is my blade view :
{{ Form::select('id_jurusan',['' => 'Pilih Jurusan']+$data ,1,['id' => 'jurusan', 'style' => 'display:inline-block','class' => 'blue-text']) }}
I just wanna get the data from table jurusan and fetch to the select ?? how to do that?? Thanks in advance, and sorry for my bad grammar.

Change your model.
protected $table = 'mahasiswa';
protected $fillable = ['nim','nama','alamat','jenis_kelamin','no_tlp','email','tempat','tanggal','link','id_jurusan'];
public function jurusan(){
return $this->belongsTo('App\Jurusan','id_jurusan','id');
}
And i think this enough your solutions for controller,
public function create()
{
$data= Jurusan::get()->pluck('name','id');
return view('Mahasiswa.mahasiswaInsert',compact('data'));
}

Related

How to use Eloquent relationships with Yajra Datatables?

I am trying to use eloquent relationships to display the name of the patient instead of the patient id foreign key. Instead it only displays the patient id as if it doesn't see the relationship.
My controller function is:
public function getActions(){
$data = Action::all();
return DataTables::of($data)
->addColumn('name',function(Action $action){
return empty ($action->patient->first_name) ? $action->patient_id : $action->patient->first_name;
//return DB::raw("SELECT * FROM 'patients' WHERE 'patients_id' = ?", $action->patient_id);
})
->make(true);
}
My js function in the view is:
<script type="text/javascript">
$(document).ready(function (){
$('#actionTable').DataTable({
processing: true,
serverSide: true,
ajax:'{!! route('get.actions')!!}',
columns:[
{data:'action_id', name:'action_id'},
{data:'name', name:'name'},
{data:'action_status_id', name:'action_status_id'},
{data:'is_complete', name:'is_complete'},
]
});
})
</script>
My Action class is:
class Action extends Model
{
protected $table ="actions";
protected $fillable=[
'user_id', 'patient_id', 'option_id', 'action_status_id', 'is_complete', 'due_date',
];
protected $primary_key = "action_id";
public $incrementing = false;
public function patients(){
return $this->belongsTo('App\Patient','patient_id','action_id');
}
}
My Patients class is:
class Patient extends Model
{
protected $table ="patients";
protected $fillable=[
'first_name', 'last_name', 'email', 'phone', 'dob', 'gender_id', 'is_active',
];
protected $primary_key = 'patient_id';
public $incrementing = false;
public function actions(){
return $this->hasMany('App\Action','action_id','patient_id');
}
}
The problem is that you have named your relation function inside your Action model as "patients". And you are calling
$action->patient->first_name.
I suggest renaming the relation function inside your Action Model to
public function patient()
It makes more sense.
Please refer to the documentation for more clarification One to One Relationships

Trying to get property of non - object Laravel 5.4

im still newbie, and trying to save data from REAXML file.
vendor for parsing REAXML from https://github.com/i4ucode/reaxml
Route:
Route::get('/admin/synctest', 'Admin\\AdminController#synctest');
Model Property
class Property extends Model
{
protected $table = 'properties';
protected $primaryKey = 'id';
protected $fillable = ['refID', 'propkind_id', 'other column'];
public function Kind()
{
return Propkind::findOrfail($this->propkind_id)->name;
}
//other public function
}
Model Propkind
class Propkind extends Model
{
protected $table = 'propkinds';
protected $primaryKey = 'id';
protected $fillable = ['id', 'name', 'slug'];
public function Property(){
return $this->hasMany('App\Property');
}
//other public function
}
Controller
public function synctest()
{
// get new class
$processor = new \REA\XmlProcessor();
$directories = Storage::disk('reaxml')->files();
foreach ($directories as $zipFile) {
//get XML file
$files = file_get_contents(url('feed/' . $zipFile));
//process the xml
$properties = $processor->parseXmlString($files);
//loop
foreach ($properties as $property) {
Property::updateOrCreate(
['refID' => $property->getRefID()],
[
//other code
'propkind_id' => Propkind::where('name', $property->getCategoryNaskleng())->first()->id, ===> ErrorException (E_NOTICE) Trying to get property of non-object
]
);
}
}
}
this piece of code Propkind::where('name', $property->getCategoryNaskleng())->first()->id)
==>show data but trow
ErrorException Trying to get property of non-object.
some kind of enlightenment, wisdom, very appreciate.
the difference between dd() and dump() is that dd() stops the execution of the script (die), dump() shows a representation of the argument but it doesn't stop the script.
for this reason I guess that the error (notice) comes after the excution of this piece of code you have posted.
clearly one of the values of $properties doesn't return a model
after several hours i found that null is the problem.
thank you #Devon for insight. #simonecosci and #Leena Patel for your comment.

Model relationship creation uses the wrong field in Laravel

I want to create a new model using the relationship between a two model module and chapter and they have HasMany relationship between them as follow :
//Module mode
public function chapters()
{
return $this->hasMany(Chapter::class, 'module_slug', 'slug');
}
//Chapters Model
public function module()
{
return $this->belongsTo(Module::class, 'module_slug', 'slug');
}
And here's how I'm storing the models :
$module = Module::create([
'title' => $request->module_title,
'icon' => $request->module_title
]);
$module->chapters()->create([
'pdf_url' => $path,
'title' => $request->chapter_title
]);
The Issue :
The problem I got is that the $module->chapters()->create() is using the id not the slug which I'm specifying as the primary key like this :
//Module model
protected $primaryKey = 'slug';
protected $keyType = 'string';
//Chapters model
protected $primaryKey = 'slug';
protected $keyType = 'string';
I don't know why it uses the id field like this screenshot :
Add this to your models:
public $incrementing = false;

Relationship hasone trying to get property of non-object

I got a problem with relationship one to one mechanism for edit & update condition, so I have model Siswa and Telepon, with Telepon belongs to Siswa... here is the code
Siswa.php (model)
class Siswa extends Model
{
protected $table = 'siswa';
protected $fillable = [
'nisn',
'nama_siswa',
'tgl_lahir',
'jns_klmin'
];
protected $dates = ['tgl_lahir'];
public function getNamaSiswaAttribute($nama_siswa){
return ucwords($nama_siswa);
}
public function setNamaSiswaAttribute($nama_siswa){
$this->attributes['nama_siswa']=ucwords($nama_siswa);
}
public function telepon(){
return $this->hasOne('App\Telepon', 'id_siswa');
}
}
Telepon.php (model)
class Telepon extends Model
{
protected $table = 'telepon';
protected $primKey = 'id_siswa';
protected $fillable = [
'id_siswa',
'no_telepon',
];
public function siswa(){
return $this->belongsTo('App\Siswa', 'id_siswa');
}
}
Edit and update function controller shown as follows :
public function edit($id){
$siswa = Siswa::findOrFail($id);
$siswa->no_telepon = $siswa->telepon->no_telepon;
return view('siswa.edit', compact('siswa'));
}
public function update(Request $request, $id){
$siswa = Siswa::findOrFail($id);
$input = $request->all();
$validator = Validator::make($input, [
'nisn'=>'required|string|size:4|unique:siswa,nisn,'.$request->input('id'),
'nama_siswa'=>'required|string|max:30',
'tgl_lahir'=>'required|date',
'jns_klmin'=>'required|in:L,P',
'no_telepon'=>'sometimes|numeric|digits_between:10,15|unique:telepon,no_telepon,'.$request->input('id').',id_siswa',
]);
if ($validator->fails()) {
return redirect('siswa/'.$id.'/edit')->withInput()->withErrors($validator);
}
$siswa->update($request->all());
$telepon = $siswa->telepon;
$telepon->no_telepon = $request->input('no_telepon');
$siswa->telepon()->save($telepon);
return redirect('siswa');
}
I got Trying to get property of non-object error in edit function, line "$siswa->no_telepon = $siswa->telepon->no_telepon;".
When we call edit view inside edit controller, it will give a form which inside of it has previous saved data. no_telepon itself is a column from Telepon table, not Siswa, so how to show telephone saved data for editing purposes is the problem. FYI, create works just fine, and no_telepon data saved in Telepon table. So, how about this one? Any help appreciated.
It's probably because you don't have any 'App\Telepon' in the database with 'id_siswa' pointing to the id of the record from table siswa.
You can ommit this error in this way:
public function edit($id){
$siswa = Siswa::findOrFail($id);
$siswa->no_telepon = $siswa->telepon ? $siswa->telepon->no_telepon : '';
return view('siswa.edit', compact('siswa'));
}

laravel one to Many Relationship with multiple table, query not optimized?

I have a table call table1(i am using some pretended name for tables here) like follow
id_table1 description
And Model is Like
`
class Table1 extends \Eloquent {
public $timestamps = false;
protected $table = 'table1';
protected $fillable = [ 'description'];
protected $primaryKey = 'id_table1';
public function relation5s(){
return $this->hasMany('Relation5','id_table1','id_table1');
}
public function relation4s(){
return $this->hasMany('Relation4','id_table1','id_table1');
}
public function relation3s(){
return $this->hasMany('Relation3','id_table1','id_table1');
}
public function relation2s(){
return $this->hasMany('Relation2','id_table1','id_table1');
}
public function relation1s(){
return $this->hasMany('Relation1','id_table1','id_table1');
}
}
This table is related to 5 tables names relation_table1,relation_table2 ... and so on.
Here is a sample model code for relation tables
<?php
use Illuminate\Database\Eloquent\Relations;
class Relation1 extends \Eloquent {
public $timestamps = false;
protected $table = 'relation_table1';
protected $fillable = [ 'id_table1','idReseller', 'login', 'password', 'type','etc'];
public function childs(){
return $this->hasMany('Relation2','id_relation','id');
}
public function table1(){
return $this->belongsTo('Table1','id_table1','id_table1');
}
public function scopeActive($query){
return $query->whereRaw('type % 2 = 1');
}
public function scopeInactive($query){
return $query->whereRaw('type % 2 = 0');
}
}
`
Problem is when i query below
$level=1; // i am controlling 5 relation tables in same controller via $level from route
$class = "Relation".$level;
$collection = new $class;
$results = $collection->with('Table1')->orderBy($sort,$order)->paginate();
its working showing all result from relation table .. but its doesn't solve n+1 query problem. i mean for every row from relation1 its querying each time on table1 .. any idea how i can solve this ?
thanks in advance
You code is correct, just replace "Table1" by "table1":
$results = $collection->with('table1')->orderBy($sort,$order)->paginate();
Take a look at Eager loading, you are using it with the with method so it will load them in the first query
$level=5
$class = "Relation".$level::with('Table1')->orderBy($sort,$order)->paginate();

Resources