Controller For One To Many Relationships - laravel

I'm using Laravel 5.2.
I have 3 tables (writters, publishers and categories) all of the is One to Many Relationships with table named books.
I'm not really sure what the problem is, but everytime i call the the column from 2 of them (nama_penerbit from publishers table and nama_kategori from categories table)from my view blade, it throws me an error Trying to get property of non-object
Here is my models
Book.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
protected $fillable = [
'judul',
'label',
'isbn',
'tanggal_terbit',
'status',
'id_penulis',
'id_penerbit',
'id_kategori',
];
// Book with Writter
public function writter()
{
return $this->belongsTo('App\Writter', 'id_penulis');
}
// Book with Publisher
public function publisher()
{
return $this->belongsTo('App\Writter', 'id_penerbit');
}
// Book with Category
public function category()
{
return $this->belongsTo('App\Writter', 'id_kategori');
}
}
Publisher.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Publisher extends Model
{
protected $fillable = [
'nama_penerbit',
];
// Relation Book with Publisher
public function book() {
return $this->hasMany('App\Book', 'id_penerbit');
}
}
Writter.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Writter extends Model
{
protected $fillable = [
'nama_penulis',
];
// Relation Book with Writter
public function book() {
return $this->hasMany('App\Book', 'id_penulis');
}
}
Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = [
'nama_kategori',
];
// Relation Book with Category
public function book() {
return $this->hasMany('App\Book', 'id_kategori');
}
}
my-view.blade.php
<span>{{ $book->writter->nama_penulis }}</span> // works like a charm
<span>{{ $book->publisher->nama_penerbit }}</span> // throw me an error
<span>{{ $book->category->nama_kategori }}</span> // throw me an error
My question is why nama_penerbit and nama_kategori throw a error while the other one works well
Any sugestion?

You're using Writter model for all three relationships, so fix these relationships by setting correct models:
// Book with Publisher
public function publisher()
{
return $this->belongsTo('App\Publisher', 'id_penerbit');
}
// Book with Category
public function category()
{
return $this->belongsTo('App\Category', 'id_kategori');
}

Related

laravel filter on relationship

hi i have this relationships with these 3 models
Customers
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customers extends Model
{
public $primaryKey = 'id';
protected $fillable = [
'contr_nom',
'contr_cog',
'benef_nom',
'benef_cog',
'email',
'polizza',
'targa',
'iban',
'int_iban',
'cliente',
];
public function claims()
{
return $this->hasMany(Claims::class);
}
public function refunds()
{
return $this->hasManyThrough(Refunds::class, Claims::class);
}
}
Claims
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Claims extends Model
{
public $primaryKey = 'id';
protected $fillable = [
'dossier',
'date_cla',
];
public function refunds()
{
return $this->hasMany(Refunds::class);
}
public function customers()
{
return $this->belongsTo(Customers::class,'customers_id');
}
}
and Refunds
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Refunds extends Model
{
public $primaryKey = 'id';
protected $fillable = [
'date_ref',
'status_ref',
'disactive',
];
public function services()
{
return $this->belongsToMany(Services::class)
->withPivot(['services_id','services_amount','services_status']);
}
public function claims()
{
return $this->belongsTo(Claims::class,'claims_id');
}
}
i have this in the controller (part of the code)
$data = Claims::with(array('customers'=>function($query){
$query->select('id','contr_nom','contr_cog','targa','email','gcliente');
}))->get();
it works, i can get customers information (parent table) for each dossier ( i put in a datatables)
But i cannot insert another filter based on Refunds table.
I need to show only dossiers where
['status_ref', '>',4]
the problem is that status_ref is in Refunds table
i tried to do somthing like this but no works
$data = Claims::with(array('customers'=>function($query){
$query->select('id','contr_nom','contr_cog','targa','email','gcliente');
}))->refunds()
->where('status_ref', '>',4)
->get();
I cannot understand why....
Thx
You have to use whereHas like:
$data = Claims::with(array('customers'=>function($query){
$query->select('id','contr_nom','contr_cog','targa','email','gcliente');
}))
->whereHas('refunds', function (Builder $query) {
$query->where('status_ref', '>', 4);
})
->get();

Cannot establish relationship between two tables in Laravel

I want to create a relation between lising and attribute table in laravel for that i have used following code to establish relationship between them but the data in my view is not coming from both the tables. I'm getting following error:
Call to undefined relationship [adListAttributes] on model
[App\Models\AdListing].
Here listing can have as many attribute associated with and attributes
can be associated to many listings
ad_listings:
id
title
name
date
ad_list_attributes table :
id
listing_id
name
namespace App\Models;
use Eloquent;
use Illuminate\Database\Eloquent\Model;
class AdListAttribute extends Model
{
protected $table = "ad_list_attributes";
public function Listings()
{
return $this->belongsToMany('AdListing', 'id', 'listing_id');
}
}
namespace App\Models;
use Eloquent;
use Illuminate\Database\Eloquent\Model;
class AdListing extends Model
{
protected $table = "ad_listings";
public function Attributes()
{
return $this->belongsToMany('AdListAttribute', 'listing_id', 'id');
}
}
Problem is that you are using belongsToMany in both the models.This will cause a problem.
In AdListAttribute model,
public function listing_information()
{
return $this->belongsTo('App\AdListing', 'id', 'listing_id');
}
In AdListing model,
public function adlisting_attributes()
{
return $this->hasMany('App\AdListAttribute', 'listing_id', 'id');
}
You can get the results using,
$response = AdListing::get();
if($response->adlisting_attributes)
{
foreach($response->adlisting_attributes as $attribute)
{
echo $attribute->name;
}
}
Problem is that ur not calling the relationship with the right name i assume
$listings = AdListing::with('Attributes')->get();
Update :
Try this :
use App\Models\AdListAttribute;
//
return $this->belongsToMany(AdListAttribute::class, 'listing_id', 'id');
Same for other model, then try

insert data to table pivot use form and show it index.blade.php in laravel 5.7

I have form create team.blade.php below this
Form Team index.blade.php
display the name of the one-team user with that user, and display the project that is being done by the user, and display the user as what (role).
the relationship of one user has many teams. and one team has many users. therefore, I choose many to many relations. but when I create team, I want to insert user_id and team_id in the pivot user_teams table as the relation table between user and team.
but when I tried to create team failed, he did not save data to the user_teams table.
and in the team index, he does not display the name of a team user with that user, and displays the project that is being done by the user, and displays the user as what.
my user models
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Presence;
use App\Models\Project;
use App\Productivity;
use App\Sick_leave;
use App\Annual_leave;
use App\Models\Team;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'role_id',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function role()
{
return $this->belongsTo(Role::class, 'role_id');
}
public function teams()
{
return $this->belongsToMany(Team::class, 'user_teams');
}
public function projects()
{
return $this->belongsToMany(Project::Class, 'user_projects');
}
}
Team Models
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\User;
use App\Role;
use Auth;
class Team extends Model
{
use SoftDeletes;
protected $table = 'teams';
protected $fillable = [
'id',
'project_id',
];
public function users()
{
return $this->belongsToMany(User::class, 'user_teams');
}
public function project()
{
return $this->belongsTo(Project::class);
}
public function role()
{
return $this->belongsTo(Role::class);
}
}
Project Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Project extends Model
{
use SoftDeletes;
protected $table = 'projects';
protected $fillable = [
'project_id',
'project_name',
'start_date',
'end_date',
'project_category',
];
public function users()
{
return $this->belongsToMany(User::class, 'user_projects');
}
public function team()
{
return $this->hasOne(Team::class);
}
}
UserTeam model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class UserTeam extends Model
{
use SoftDeletes;
protected $table = "user_teams";
public function team()
{
return $this->belongsTo(Team::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
Team Controller
public function index()
{
$users = auth()->user()->name;
$users = User::all();
return view ('teams.index', compact ('teams', 'users', 'projects'));
}
public function create()
{
$users = User::all();
$projects = Project::pluck('project_name', 'id');
return view ('teams.form', compact('projects', 'users'));
}
public function store(Request $request)
{
$team = Team::create($request->all());
$userIds = User::find(2);
$team->users()->attach($userIds);
return redirect()->route('team.create');
}
In user_teams has fields user_id and team_id. how do i overcome this??
You have to create the team and then attach the users that belong to it.
Example from the docs:
Attaching
Eloquent also provides a few additional helper methods to make working
with related models more convenient. For example, let's imagine a user
can have many roles and a role can have many users. To attach a role
to a user by inserting a record in the intermediate table that joins
the models, use the attach method:
$user = App\User::find(1);
$user->roles()->attach($roleId);
In your case:
Team Controller
public function store(Request $request)
{
$team = Team::create($request->except('user_id'));
$team->users()->attach($request->get('user_id', []));
return redirect()->route('team.create');
}

Laravel Method sync does not exist

Post Model
<?php
namespace App\Model\User;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function tags(){
return $this->belongsToMany('App\Model\User\Tag','post__tags', 'post_id', 'tag_id');
}
public function categories() {
return $this->belongsToMany('App\Model\User\Category','category__posts','post_id', 'category_id');
}
}
Category Model
<?php
namespace App\Model\User;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function posts(){
return $this->belongsToMany('App\Model\User\Category','category__posts', 'post_id', 'category_id');
}
}
Tag Model
<?php
namespace App\Model\User;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
public function posts() {
return $this->belongsToMany('App\Model\User\Post','post__tags','post_id','tag_id');
}
}
PostController.php
public funcion store()
{
// do validation here
try{
$post = new Post;
$post->title = $request->title;
$post->subtitle = $request->subtitle;
$post->slug = $request->slug;
$post->body = $request->body;
$post->status = 1;
$post->save(); // This works correct
$post->tags->sync($request->tags); // Not working
$post->categories->sync($request->categories); // Not working
}
catch(\Exception $e){
return redirect(route('post.index'))->with('message', 'Error Adding Post into system!'.$e->getMessage()); // getting Message "Method sync does not exist. "
}
}
Sync is a method on the builder instance, you're using it on the collection.
// change your code like this
$post->tags()->sync($request->tags);
$post->categories()->sync($request->categories);
You need to use the following:
$post->tags()->sync($request->tags);
$post->categories()->sync($request->categories);
Don't forget the () in tags and categories
$post->categories without () is a Collection instance.
$post->categories() is a belongsToMany instance

Multiple Laravel Eloquent Relationship

I got stacked in laravel eloquent relationships. Here's the scenario:
I have 4 tables in my database:
Categories,
Courses,
Lessons, and
Lesson_items.
I have 3 more tables:
category_course,
course_lesson, and
lesson_item_lesson.
Now, I have these codes:
Category.php - model
class Category extends Model
{
public function courses(){
return $this->belongsToMany('App\Course');
}
}
routes.php - routes
Route::get('/category/{id}', [
'uses' => 'LearnController#getCategories'
]);
MyController.php - controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Category;
use App\Lesson;
class LearnController extends Controller
{
public function getCategories($id){
$categories = Category::find($id);
$lessons = Lesson::find($categories);
return view('categories', compact('categories', 'lessons'));
}
}
Now, The result that I want is this:
Really need your help guys.
You need nested eager laoding
Category.php
class Category extends Model
{
public function courses(){
return $this->belongsToMany('App\Course');
}
}
Course.php
class Course extends Model
{
public function lessons(){
return $this->belongsToMany('App\Lesson');
}
}
Lesson.php
class Lesson extends Model
{
public function lessonItems(){
return $this->belongsToMany('App\LessonItem');
}
}
LessonItem.php
class LessonItem extends Model
{
public function lessons(){
return $this->belongsToMany('App\Lesson');
}
}
Then in controller
class LearnController extends Controller
{
public function getCategories($id){
$categories = Category::with('courses.lessons.lessonItems')->find($id);
return view('categories', compact('categories'));
}
}
Edit
You need some kind of this construction
#foreach ($category->courses as $course) {
#foreach ($course->lessons as $lesson) {
#foreach ($lesson->lessonItems as $item) {
#endforeach
#endforeach
#endforeach

Resources