
Call to undefined relationship [user] on model [App\Models\Post]
Sometimes we got error Call to undefined relationship [user] on model [App\Models\Post] while calling relationship method using with() on model without defining the method in model class.
Answers 1
-
Get user/author detail using belongsTo relation on post model
//app\Models\Post.php class Post extends Model { //Add user method in existing post model public function user(){ return $this->belongsTo('App\Models\User'); } } //Code snippet to get the user/author details with post. $data = Post::with('user')->first(); dd($data); //Import post model after the namespace in controller or anywhere you want to use the above code use App\Models\Post;
0You have to create a user method with belongsTo relationship in the post model. It helps you to get the user or author information using the user_id (foreign_id) of the posts table and id (primary key) column of users table.
Random Code Snippet Queries: Laravel
- The POST method is not supported for this route. Supported methods: PUT.
- Root composer.json requires php ^7.3 but your php version (8.0.0) does not satisfy that requirement
- Seed database using SQL file in Laravel
- Pass variable from blade to controller Laravel
- Laravel 7 login error message not showing
- How to pass link from controller to view in laravel on ajax call
- Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
- How to get single column value in laravel
- How to check if user has created any post or not in laravel
- Get comma separated email from input array
- How to add unique records in pivot columns of Laravel pivot table
- The openssl extension is required for SSL/TLS protection but is not available
- Get today records in Laravel
- How to create pivot table in laravel using migration
- Laravel 9 pagination with search filter
- How to implement toggleLike() method in Overtrue\LaravelLike laravel package
- Laravel route redirect not working
- How to send ID to another page in Laravel
- Import/Use Storage facade in laravel
- How to pass query string to url in laravel
- Fatal error: Uncaught Error: Class "Illuminate\Foundation\Application" not found
- How to get random string in Laravel
- Rendering HTML from database table to view in Laravel
- How to get data from two tables in laravel
- Touch parent updated_at in Laravel