How to add my course Slug before lecture in url path? - laravel

i'm currently doing a project for my homework, which i didn't managed to see something like this to fix my problem.
I have 2 models with Course and CourseLecture name. and i'm using getPathAttribute in my class base on a tutorial in internet.
in my Course Model i'm using getPathAttribute like this :
public function getPathAttribute()
{
return "/clientside/instructor/courses/$this->slug";
}
and in my CourseLecture Model :
public function getPathAttribute()
{
return "/clientside/instructor/courses/{course}/lectures/$this->slug";
}
I need to put my course slug to this getPathAttribute like :
http://url.com/clientside/instructor/courses/php/lectures/one
also my CourseLecture is using course_id and i've got a relationship between them which, they're belongsTo' andHasMany'. so how can i add course slug base on this structor in this path?
Also for this homework, i'm using Vue.js/Laravel. and it's a spa. i've tagged vue.js bcs if there's any solution to fix this via router, I will be happy to use it.

You can dynamically grab course slug from the course() relationship defined on the CourseLecture model. See below:
In CourseLecture model:
protected $appends = ['path'];
// relationship
public function course()
{
return $this->belongsTo(Course::class);
}
public function getPathAttribute()
{
return "/clientside/instructor/courses/{$this->course->slug}/lectures/$this->slug";
}

Related

Laravel Eloquent Relation belongsTo update

I am trying to update/delete/create in belongsTo relations.
Company has many sports
sports is belonging to Company
Here is two models.
class CompanySports
{
public function company()
{
return $this->belongsTo(Company::class, "company_id","id");
}
class Company
public function sports()
{
return $this->hasMany(CompanySports::class,"company_id","id");
}
}
at controller, when sports is added or modified or remove, what is the best practice to update?
i know that many to many, sync can be used. In this, what is the best solution? Should i compare everytime after loading all from database which is not good practice i believe.
From your code, I would first recommend putting your models in separate files, and ensuring they are singular. If you use the artisan make:model command to generate the stubs, it should do this for you.
// app/CompanySport.php // <-- NOTE singular
class CompanySport // <-- NOTE singular
{
public function company()
{
return $this->belongsTo(Company::class, "company_id","id");
}
}
// app/Company.php
class Company {
public function sports()
{
return $this->hasMany(CompanySport::class,"company_id","id"); // singular
}
}
From there, I find it helpful to build helper methods in the various classes so that the grammar sounds natural and more importantly, belongs to the model. For example:
// app/Company.php
class Company
{
...
public function addSport(CompanySport $sport)
{
$this->sports()->save($sport);
}
public function removeSport(CompanySport $sport)
{
$this->sports()->find($sport->id)->delete();
}
}
These helper functions can then be easily called from anywhere, e.g. controller:
// CompanySportsController.php
public function store(Company $company, CompanySport $sport)
{
$company->addSport($sport);
return redirect('/company/' . $company->id);
}
If you are using these helpers, there is no comparing or sync to be done since you are only using a one to many relationship. Eloquent does everything for you.
Also, I've found this cheatsheet particularly helpful when building out the initial relationships and scaffolding of a new app.
While adding new record of Company Model, you need not to do anything as there is no child for it yet.
While updating an instance of a Company model, again you need not to update anything on its children. As relationship are based on id(primary key) which I believe you don't change while updating.
And now for deleting there are some questions. Do you want to delete the children when the parent is deleting? If so, you can use ON DELETE CASCADE which you can set up in migration like
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
in your spors table.
Well you can make your own function too like answered in here
Well if you don't want to delete the children, you can use softdelete on your Model. set up the relations then like
CompanySports
public function company()
{
return $this->belongsTo(Company::class, "company_id","id")->withTrashed();
}
This way you can get the parent of a children without any error though the parent is deleted.

A model with polymolymorphic ony to many and simple one to many relationship

I am using laravel 5.7. I have now a situation where i have a Fight model with structure user_id, fightable_id
i have two other tables users and monsters. so users_id refers to users (a user can have many fights) and fightable_id can refer to either a user or a monster (monsters table). so I have to define the functions for the relation ship
for User model i have to do
1.for polymorphic one to many relationship
public function fights()
{
return $this->morphMany('App\Fight', 'fightable');
}
2.for simple one to many relationship
public function fights()
{
return $this->hasMany('App\Fight');
}
I am confused now. ofcourse the only way is to change the functions name. but i will be doing the correct thing by changing the function names right (as both the functions have same name). or is there anything I am doing wrong?
I'm not sure I understand your question completely but I'll try my best!
Also this post will really help you understand the problem you are facing I think,
Laravel morph relationship
Using the code from the post I linked but taking your tables would produce models defined like this.
User Model
class User extends Model
{
public function fights()
{
return $this->hasMany('App\Fight');
}
}
Fight Model
class Fight extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
public function fightable()
{
return $this->morphTo();
}
}
Monster Model
class Monster extends Model
{
public function fight()
{
return $this->morphOne('App\Fight', 'fightable');
}
}
If you still feel this has not answered your question or need some more help just let me know!

How to setup conditional relationship on Eloquent

I have this (simplified) table structure:
users
- id
- type (institutions or agents)
institutions_profile
- id
- user_id
- name
agents_profile
- id
- user_id
- name
And I need to create a profile relationship on the Users model, but the following doesn't work:
class User extends Model
{
public function profile()
{
if ($this->$type === 'agents')
return $this->hasOne('AgentProfile');
else
return $this->hasOne('InstitutionProfile');
}
}
How could I achieve something like that?
Lets take a different approach in solving your problem. First lets setup relationship for the various models respectively.
class User extends Model
{
public function agentProfile()
{
return $this->hasOne(AgentProfile::class);
}
public function institutionProfile()
{
return $this->hasOne(InstitutionProfile::class);
}
public function schoolProfile()
{
return $this->hasOne(SchoolProfile::class);
}
public function academyProfile()
{
return $this->hasOne(AcademyProfile::class);
}
// create scope to select the profile that you want
// you can even pass the type as a second argument to the
// scope if you want
public function scopeProfile($query)
{
return $query
->when($this->type === 'agents',function($q){
return $q->with('agentProfile');
})
->when($this->type === 'school',function($q){
return $q->with('schoolProfile');
})
->when($this->type === 'academy',function($q){
return $q->with('academyProfile');
},function($q){
return $q->with('institutionProfile');
});
}
}
Now you can access your profile like this
User::profile()->first();
This should give you the right profile. Hope it helps.
you can do this by use another method please check this:
a blog Post and Video model could share a polymorphic relation to a
Tag model. Using a many-to-many polymorphic relation allows you to
have a single list of unique tags that are shared across blog posts
and videos. First, let's examine the table structure:
https://laravel.com/docs/5.4/eloquent-relationships#many-to-many-polymorphic-relations
Looks like that should be $this->type rather than $this->$type - since type is a property, not a variable.

How do i access data using two BelongsTo?

I have three tables - "courses", "lessons" and "tasks". Each lesson belongsTo a course, and each task BelongsTo a lesson. I want to output a task, showing the task name, the lesson name, and the course name. How do I access the course table data? To get the lesson information linked to a course, I have used the following in my Task model:
$lessonName = $this->lessons->lesson_name;
To get the course name associated to that lesson, I have tried the following with no success, but I am really guessing here:
$courseName = $this->lessons->courses->course_name;
My model relationships are as follows:
Course.php
public function lessons()
{
return $this->hasMany('App\Lesson');
}
Lesson.php
public function tasks()
{
return $this->belongsTo('App\Task', 'task_id', 'id');
}
Task.php
public function lessons()
{
return $this->belongsTo('App\Lesson', 'lesson_id', 'id');
}
Where am I going wrong? Thanks
there is another way you can do this by using accessors.
on your Task model do the following:
public function getLessonAttribute(){
return Lesson::where('id', $this->attributes[*foreign_key_field*])->first();
}
Here you receive all the data regarding the lesson that the task belongs to, and can use them as any other attribute (field) of the model.
on your Lesson model get the course that it belongs to.
public function getCourseAttribute(){
return Course::where('id', $this->attributes[*course_foreign_key_field*])->first();
}
and then assuming that $task is your collection, you can access the lesson and the course like the following in blade:
$task->lesson->lesson_name and $task->lesson->course->course_name
In your lesson.php model doesn't exist relationship courses so there are your issue. Use answer what is told you #jeroenF
So you want the inverse of hasManyThrough?
The hasManyThrough feature of Laravel (see their site) facilitates connecting your Courses to Task directly, without having the intermediate connection in a separate relationship.
You are looking for the inverse?

Ordering table data

I already read this piece from the laravel 5.1 documentation:
$users = DB::table('users')
->orderBy('name', 'desc')
->get();
I have no ideia where to write that.
And this is what I tried to write inside my Model:
class Professor extends Model
{
$professor = DB:table('professor')->orderBy('name','asc')->get();
}
Also tried:
class Professor extends Model
{
Professor::orderBy('name')->get();
//$professor = Professor::orderBy('name')->get();
}
Nothing works e.e
All of them give me erros like:
syntax error, unexpected '$professor' (T_VARIABLE), expecting function (T_FUNCTION)
The piece of code your trying to write should not be placed inside a Model. It should be in a controller or a repository if your using a Repository Pattern.
Assuming you got the following in your code.
A table called professors. A model Professor . A Controller called ProfessorsController.
And a route file with the following code get('professors','ProfessorsController#index');
Then on the controller you should have the following code.
class ProfessorsController extends Controller {
public function index()
{
$professors = \DB:table('professors')->orderBy('name','asc')->get();
return view('proffesors')->with('proffessors',$professors);
}
}
This will return an order list of professors to the view. That is if you are using a view to represent the data.
It does not need to be in model. Most of time something like that goes in controller.
In model you need to define relations or functions that would be used application wide on a object.
If you want to do something similar in model you won't use DB::table you need something like:
class Professor extends \Eloquent
{
public function professorsByName(){
$professionCollection = Professor::all()->orderBy('name','asc')->get();
return $professionCollection;
}
}
Please take it as example it's not something that should go in model at least this simple not.
Mental Note
Never use DB::table reason your observer if any won't execute.
I think you all are missing the primary issue with
class Professor extends Model
{
$professor = DB:table('professor')->orderBy('name','asc')->get();
}
This is not how PHP classes work.
OP, you need to brush up on the concepts of OOP.
What you need is something like this:
your controller:
public function myRoutedMethod()
{
$professors = Professor::getModel()->orderBy('name','asc')->get();
foreach($professors as $professor)
{
var_dump($professor->toArray();
}
}
Or probably even better, create a repository to interface with your model and just call $repository->professors()->toArray();
Google search: Laravel Repository

Resources