Reputation: 111
Here is the current code I have for the model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Courses extends Model
{
protected $table = 'courses';
foreach ($courses as $course) {
echo $course->course;
}
}
Is this coded correctly? The data is being fetched from the 'courses' table and 'courses' is the name of the column.
I am adding a new feature to my search directory. The profiles contain variables from the database so there is a lot of data being fetched from the same database table. There is one data, however, that is being put into a separate table because it can't fit in the same table as the other data. So I have to figure out a way to fetch that data from the other database table and put it into the profile code.
Here is the controller for the profile page (the snippet that controls the view):
//view school
public function viewschool ($url){
$url ='schools/' . $url;
if (count(School::where('url', '=', $url)->first()) <> 1 ) {
return redirect()->back();
}
$sch = School::where('url', '=', $url)->first();
$articles = posts::where('post_type','article')->where('school',$sch->name)->take(3)->get();
$news = posts::where('post_type','news')->where('school',$sch->name)->take(3)->get();
$others = posts::where('post_type','news')->take(3)->get();
return view('school-info')
->with(array('sch' => $sch,'school_articles' => $articles,'school_news' => $news,'others' => $others));
}
The new data are the school courses. the database table for courses contain columns for school ID (basically the courses are matched up to the ID of the school name they belong to in the schools table) as well as other data such as duration of course and tuition.
Am wondering how do I create the controller code for the school courses?
Upvotes: 0
Views: 91
Reputation: 152
So first improve your understanding of the Model in Laravel. You just define the properties for your classes there. The foreach
is totally out of place there.
An example Model should look like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Course extends Model
{
protected $table = 'courses';
protected $fillable = ['properties'];
}
So you would've start with a "fresh" and ready to use Model. Every Action with your Model you do inside your Controller. But DB Queries you do inside a Repository.
And now regarding your Question:
You can define relationships within Models via e.g.
protected $searchable =
[
'relations' => [
'schools' => [
'foreignKey' => 'school_id',
'foreignField' => 'courses'
]
]
]
Edit: forgot the method inside the model :D
public function schools(): BelongsTo
{
return $this->belongsTo(Schools::class);
}
Upvotes: 1