Eloquent relationship in Laravel - laravel

I'm having following table structure:
Table Name - Users
Column: id, name, email, etc
Table Name - Plugins
Column: id, theme_id, type_id, code,
Table Name - Templates
Column: id, theme_id, user_id, templatedata
Table Name - Userplugins
Column: id, user_id, plugins_id, contents
Now I'm calling the route with id of the templates, in which templatedata has JSON data, i'm able to get Plugins code by following code in my blade file as:
#foreach($gettemplate as $renderer)
{!! $plugins->find($renderer)->code !!}
#endforeach
but I'm unable to fetch contents in the UserPlugins table. Following is my controller where I'm trying to do so:
public function get_template($id)
{
$template = Template::findOrFail($id);
$gettemplate = json_decode($template->templatedata);
$plugins = Plugins::all();
$user = User::findorFail($id);
return $user->userplugins()->contents;
//return view('nitseditor.test', ['plugins' => $plugins, 'gettemplate' => $gettemplate, 'user' => $user]);
}
I've commented out my view just to check the output.
I've defined the relationship in the model my App/User.php file contains:
public function userplugins(){
return $this->hasMany('App\UserPlugin');
}
And in App\UserPlugin.php file I've:
protected $fillable = [
'contents',
];
I'm getting the following error:
Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$contents
Please help me out, Thanks.

In the following line:
return $user->userplugins()->contents;
When you call $user->userplugins() that mean you call an relation method. It's will not return Eloquent Collection or Eloquent Object for you.
You need to call
$user->userplugins
to get collection of UserPlugin
However, when you call
return $user->userplugins->contents;
you will get error, becauese return $user->userplugins is an Eloquent Collection, you can not get contents from it.
You can get the contents of specific UserPlugin. For example, the first UserPlugin of user like:
return $user->userplugins()->first()->contents;

Related

How do I return the ID field in a related table in Laravel request

I have two related tables and I want to return all fields including the ID (key) field. My query below returns all fields except the ID. how do I return the ID field from one of the tables?
'programmes' => ProgrammeInstances::with('programmes')->get(),
the query below returns Unknown column 'programmes.programme_title' as it is looking for it in the table 'programme_instances'
'programmes' => ProgrammeInstances::with('programmes')->select('programmes.programme_title', 'programmeInstances.id', 'programmeInstances.name', 'programmeInstances.year')->get(),
Laravel provides multiple relationships, one of these is the hasMany() relationship which should return a collection where a User hasMany rows inside of your database
For example, inside your User model :
public function programmes() {
return $this->hasMany(Program::class);
}
Now in your controller, you can do :
public function edit($id) {
$programmes = User::find($id)->with('programmes')->get();
return view('user.edit')->with('programmes', $programmes);
}
And then you can loop over it inside your view
#forelse($programmes->programmes as $program)
// provide the data
#empty
// the user doesn’t have any programmes
#endforelse
a solution i found below - still not sure why ID isnt automatically returned when i get all fields, but works when i specify individual fields:
'programmes' => ProgrammeInstances::with('programmes')
->get()
->transform(fn ($prog) => [
'programme_title' => $prog->programmes->programme_title,
'id' => $prog->id,
'name' => $prog->name,
'year' => $prog->year,
]),

how to get id from url to add it in database as a foreign key in another table

i want to get id form url and use it as a foreign key to put it in table in database
when i do it like that a got an error that tour_id column is embty
public function addtour(Request $request,$id) {
$form_data = array(
'user_id' => $request->input("user_id",auth::user()->id),
'tour_id' => $request->input("tour_id",$id),
);
tecket::create($form_data);
return view('submit_tour');
}
You want to define a route that has the id as a parameter, so something like:
Route::get('/add-tour/{id}', [TourController::class, 'addTour']); // Laravel 8
Route::get('/add-tour/{id}', 'TourController#addTour'); // Laravel 7
The {id} parameter in the URL will be passed in as the $id in your addTour function.
What you then do with the $id such as checking it is valid is up to you.

Property [***] does not exist on this collection instance

I tried doing this for a website but my 'hotel' table has both an 'id' and a 'hotel_id' column. I heard eloquent recognizes the associated table name with _id as the primary key when defining a relationship. How would I define my relationship with the comments to the hotel? I have tried this in my Hotel model
public function comments() { return $this->hasMany(Comments::class, 'hotel_id') }
this is my controller for the page
public function hotelPage($hotel_id)
{
$hotels = Hotel::select(
'hotel.hotel_id'
,'hotel.name'
,'hotel.photo_url'
,'hotel.address'
,'hotel.desc_en'
//,'hotel.hotel_url'
,DB::raw("(CASE WHEN
COALESCE(hotel.hotel_url,'')!='' THEN
LOWER(CONCAT(hotel.hotel_url,'?aid=*******'))
ELSE
CONCAT(hotel.hotel_url,'http://www.example.com/?aid=*******')
END)
as hotel_url"))
->where('hotel.hotel_id',$hotel_id)
->get();
return view('hotel.hotelPage', ['hotels' => $hotels]);
}
and when I load the view
#foreach($hotels->comments as $comment) {{$comment->body}} #endforeach
I get the error "Property [comments] does not exist on this collection instance./ / /hotelPage.blade.php"
Please help, I am using laravel 5.4

How to add data to additional column in pivot table in laravel

I'm trying to build an app in Laravel 5.3, I want to add additional column data in the pivot table. Following is my code:
My Users model:
public function relations()
{
return $this->belongsToMany('App\Plan')->withPivot('child');
}
My Plan model:
public function relations()
{
return $this->belongsToMany('App\User')->withPivot('child');
}
In my controller I'm fetching the user data from Auth::user(); and for plans and child element I'm getting through request. I want to store this to my pivot table. Following is the code which I tried in my controller:
$user = \Auth::user();
$plan_id = $request->plan_id;
$childid = $request->child_id;
$plan = App\Plan::find($plan_id);
$user->relations()->attach($plan, ['child' => $childid]);
Help me out in this.
You should use attach() like this:
$user->relations()->attach($plan_id, ['child' => $childid]);
Try the save method as:
$user->relations()->save($plan, ['child' => $childid]);
Docs
Both save and attach work. Just that attach will return null while save will return $user object when I try with tinker

Laravel orm Order by custom attribute

In my user model I have added custom attribute get number of post user have created.
I can successfully get that but when I have try to order by it give error.
1054 Unknown column 'posts' in 'order clause'
Can you let us know what is the Eloquent query you're running? Also make sure that the name of the table you're using is correct.
EDIT:
Does the posts column exist in the users table? Or are you trying to get all the posts from the Post Model and order the posts by their name in descending order?
If that is what you want to do then you would need to go to your User Model and set up your relationship with posts.
In User Model create this method:
public function posts() {
return $this->hasMany('Post'); // Post would be the name of the Posts Model
}
In Post model do this:
public function user() {
return $this->belongsTo('User'); // Where User is the name of the Users Model
}
Then according to the Laravel documentation you could do someonething like this with the query:
$users = User::with(array('posts' => function($query)
{
$query->orderBy('name', 'desc'); // assuming that 'name' would be the column in the posts table you want to sort by
}))->take(5)->get();
I hope I am correct and this helps and that solves your issue.

Resources