my model in App\Models, I've added the company_id and year to be for the primary key
class CompanyMasterCuti extends Model
{
use HasFactory;
protected $table = 'company_master_cuti';
protected $fillable = [
'company_id', 'year', 'cuti', 'created', 'created_by', 'modified', 'modified_by',
];
protected $guarded = [];
protected $keyType = 'string';
public $timestamps = false;
protected $primaryKey = ['company_id', 'year'];
public $incrementing = false;
public function company() {
return $this->belongsTo('App\Models\Company', 'company_id', 'id');
}
}
my code in controller
public function show($company_id, $year) {
$master_cuti = CompanyMasterCuti::where('company_id', $request->company_id)->where('year', $request->year)->first();
return view('master-cuti.show', compact('master_cuti'));
}
my code in index.blade.php to direct to route show
@forelse($master_cuti as $m_cuti)
<a href="{{ route('master-cuti.show', [$m_cuti->company_id, $m_cuti->year] ) }}">
<i ></i>
</a>
@endforelse
my code in show.blade.php
<div >
<div >
<ul style="padding-top: 5px !important">
<li >
<span >Tahun</span>
<span>{{ $master_cuti->year }}</span>
</li>
<li >
<span >Cuti</span>
<span>{{ $master_cuti->cuti}}</span>
</li>
</ul>
</div>
</div>
route
Route::resource('master-cuti', CompanyMasterCutiController::class);
I want to display data based on company_id and year which is the primary key of the table company_master_cuti . My code is not correct because I tried to return data from the controller the data is null, what's wrong with my code? is there any solution for my problem?
CodePudding user response:
Laravel does not support composite primary keys, check here. If you want to have a composite primary key you need to do all the work manually.
I would suggest having id
as the primary key, and define company_id, year
pair as unique
key.
You can still ignore id
as the primary key and use company_id, year
pair as primary key, but as I mentioned that would be manual work. Check out routing and controller changes.
Route::get('master-cuti/{company_id}/{year}/show', CompanyMasterCutiController::class)->name('master-cuti.show');
public function show($company_id, $year) {
$master_cuti = CompanyMasterCuti::where('company_id', $company_id)->where('year', $year)->first();
return view('master-cuti.show', compact('master_cuti'));
}