I want show $post->category->cat_name but I have an error Trying to get property of non-object!
Model : Category
class Category extends \Eloquent {
protected $guarded = array();
public static $rules = array();
public function posts(){
return $this->hasMany('Post');
}
}
Model Post
class Post extends \Eloquent {
protected $guarded = array();
public static $rules = array();
public function category(){
return $this->belongsTo('Category');
}
public function user(){
return $this->belongsTo('User');
}
public function comments(){
return $this->hasMany('Comment');
}
}
PostsController
public function show($id)
{
$post = Post::find($id);
return View::make('posts.show',compact('post'));
}
}
In View $post->post_name works.
$post->user->username works
$post->comments->content works
but $post->category->cat_name doesn't works
And I can do CRUD with categories.
So I think there is a probleme with my model Category but i don't understand
Related
before so sorry for my bad english. Whats mean that error? "Call to a member function where() on null". In my code need obtain all application for a each category.
Im interesting in use a Model route binding, its works well when I insert a one model, for example: Application. Example:
Route::get(applications/{application},'ApplicationController#show')->name('apps'));
But when I try use 2 model in a route, have this problem. Here my code:
Route::get('categories/{category}/applications/{application:category_id}','ApplicationController#show')->name('apps');
My models:
class Application extends Model{
protected $fillable = ['name', 'price', 'category_id', 'vote', 'image_src'];
public function users()
{
return $this->belongsToMany(User::class, 'applications_users_states', 'application_id', 'user_id')
->withPivot('state_id')
->withTimestamps();
}
public function categories()
{
return $this->belongsTo(Category::class);
}
public function logs()
{
return $this->belongsToMany(Log::class)->withTimestamps();
}
}
class Category extends Model
{
protected $fillable = ['name', 'description'];
public function applications()
{
$this->hasMany(Application::class);
}
}
My Controller:
public function show(Category $category,Application $application)
{
return $application;
}
Thanks for your time and for your knowledge!!!!!
public function index()
{
$query = Activity::orderBy('id','DESC')->with('provinces');
if(!Auth::user()->hasRole('Administer')){
$query=$query->where('province_id', Auth::user()->id);
}
$activities = $query->latest()->get();
return view('activity.index',compact('activities'));
}
How to display owner of a post in laravel admin list display?
My User Model
class User extends Authenticatable implements HasMedia
{
public function activities()
{
return $this->hasMany(Activity::class);
}
}
My Activity Model:
class Activity extends Model
{
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
public function provinces()
{
return $this->belongsToMany(Province::class);
}
}
My province Model
class Province extends Model
{
protected $fillable = [ 'title', 'post_id'];
public function activities()
{
return $this->belongsToMany(Activity::class);
}
public function user()
{
return $this->belongsToMany(User::class);
}
}
I want to show the content to the user by province.
And also the admin can see all the content.
please help me i am new in laravel
Based on your comment, you should change your province conditions to:
if (!Auth::user()->hasRole('Administer')) {
$query = $query->where('province_id', Auth::user()->province_id);
}
You have defined that each activity belongs to an user. So can access owner of each activity like this:
$activity->user->name;
And if your activity belongs to a province, you should define your relation in this way:
class Activity extends Model
{
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
public function province()
{
return $this->belongsTo(Province::class);
}
}
Also for your Province model:
class Province extends Model
{
protected $fillable = [ 'title', 'post_id'];
public function activities()
{
return $this->hasMany(Activity::class);
}
public function users()
{
return $this->hasMany(User::class);
}
}
And this is best practice to use eager loading for fetching related records. It will look like this one:
$query = Activity::with(['user', 'province'])->orderBy('id','DESC');
Also another hint: try to use better variable names. You can use $activities instead of $query.
We have the following class using $with:
class CargaHorasEmpleado extends Model
{
protected $table = "empleados_horas";
protected $with = ["tipoTarea", "proyecto", "empleado", "empleadoQueHizoLaCarga"];
public function tipoTarea()
{
return $this->belongsTo('App\TipoTarea', 'id_tipo_tarea', 'id')->withTrashed();
}
public function empleado()
{
return $this->belongsTo('App\Empleado', 'id_empleado', 'id')->withTrashed();
}
public function empleadoQueHizoLaCarga()
{
return $this->belongsTo('App\Empleado', 'id_empleado_cargo_hs', 'id')->withTrashed();
}
public function proyecto()
{
return $this->belongsTo('App\Proyecto', 'id_proyecto', 'id')->withTrashed();
}
}
This is the class TipoTarea
namespace App;
use Illuminate\Database\Eloquent\Model;
class TipoTarea extends Model
{
protected $table = 'tipos_tareas';
public $timestamps = false;
protected $fillable = [
'titulo', 'descripcion'
];
}
Thep page throws the error: "Call to undefined relationship [tipoTarea] on model [App\CargaHorasEmpleado]". That's the only relationship that's not working. The others are fine. What's wrong?
Well, isn't the relationship called "tipoTarea"? You wrote "tiposTarea"
The problem was that my class "TipoTarea" didn't use softdeletes. So the error was in using the "WithTrashed" method. The correct way is:
public function tipoTarea()
{
return $this->belongsTo('App\TipoTarea', 'id_tipo_tarea', 'id');
}
Occurred a problem for adding relationships categories and posts. In the database there is three tables: categories(category_id, title), posts(post_id, text,title), category_post(category_id, post_id).
Need to adding table category_post, but not adding. This is model category and post as well as their relationships.
class Category extends Eloquent{
protected $table = 'categories';
protected $primaryKey = 'category_id';
public function posts()
{
return $this->hasMany('Post');
}
}
class Post extends Eloquent
{
protected $table = 'post';
protected $primaryKey = 'post_id';
public function category()
{
return $this->belongsTo('Category');
}
//Method add post. Called in the controller
public static function add($data)
{
try {
$post = new Post;
$post->title = $data['title'];
$post->text = $data['text'];
$category = Category::find(1);
$category->posts()->save($post);
}catch (Exception $e){
return $e;
}
return $category;
}
}
Return Exception. Help me please.
trying to get some polymorphic relations working in laravel 4.
I have a CoreUserAccount table that looks like so:
core_user_account:
id
profile_id
other columns
I then have 2 other tables core_user_client_profile and core_user_consultant_profile. They both have id fields.
i am trying to link them like so:
In the CoreUserAccount model:
public function profile()
{
return $this->morphTo();
}
And in both the other tables i have:
public function user()
{
return $this->morphOne('CoreUserAccount', 'profile');
}
But i don't seem to be able to get any of the profile data through the user object. Any ideas?
Cheers
EDIT
Here is my core_user_account table:
And here are my 2 different profile type tables core_user_client_profile and core_user_consultant_profile:
Here is my model for core_user_account:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class CoreUserAccount
extends Eloquent
implements UserInterface, RemindableInterface
{
protected $table = 'core_user_account';
protected $hidden = array('password');
protected $guarded = array('id', 'password');
public function profileType()
{
return $this->belongsTo('CoreUserProfileType');
}
public function address()
{
return $this->belongsTo('CoreUserAddress', 'user_account_id', 'id');
}
public function profile()
{
return $this->morphTo();
}
public function getAuthIdentifier() {
return $this->getKey();
}
public function getAuthPassword() {
return $this->password;
}
public function getReminderEmail() {
return $this->email;
}
public function getRememberToken() {
return $this->remember_token;
}
public function setRememberToken($value) {
$this->remember_token = $value;
}
public function getRememberTokenName() {
return 'remember_token';
}
}
And my core_user_client_profile model:
class CoreUserClientProfile
extends Eloquent
{
protected $table = 'core_user_client_profile';
public function profileLanguage()
{
return $this->belongsTo('CoreUserProfileLanguages');
}
public function user()
{
return $this->morphOne('CoreUserAccount', 'profile',null,'profile_id',null);
}
}
And my core_user_consultant_profile model:
class CoreUserConsultantProfile
extends Eloquent
{
protected $table = 'core_user_consultant_profile';
public function profileLanguage()
{
return $this->belongsTo('CoreUserProfileLanguages', 'consultant_profile_id', 'id');
}
public function qualifications()
{
return $this->belongsTo('CoreUserConsultantQualifications', 'profile_id', 'id');
}
public function registration()
{
return $this->belongsTo('CoreUserConsultantRegistrations', 'profile_id', 'id');
}
public function specialities()
{
return $this->belongsTo('CoreUserConsultantProfileSpeciality', 'profile_id', 'id');
}
public function user()
{
return $this->morphOne('CoreUserAccount', 'profile');
}
}
I have read the document pointed out in the comments below and understand i seem to have to have a type column in my DB. But what data needs to be stored here? does it automatically get stored or do i have to store it?
Cheers
You should have to have profile_type, and profile_id columns. In profile_type will be stored values: 'CoreUserConsultantProfile' or 'CoreUserClientProfile'. This fields will be populated automaticlly when you save data.
This is example how save data in polymorph relation.
$profile = CoreUserConsultantProfile::find(1);
$account = new CoreUserAccount();
$profile->profile()->save($account);
So now, profile_id=1, and profile_type = 'CoreUserConsultantProfile'