Using attach() to add relationship between Model and Pivot Model - laravel

I have a pivot model for a Many-to-Many relationship called UserWebpage.
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class UserWebpage extends Pivot
{
public function collections(){
return $this->belongsToMany('App\Collection', 'collection_user_webpage');
}
}
I also have a model called Collection
namespace App;
use Illuminate\Database\Eloquent\Model;
class Collection extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
public function userWebpages(){
return $this->belongsToMany('App\UserWebpage', 'collection_user_webpage');
}
}
I'm trying to establish a Many-to-Many relationship between UserWebpage and Collection. I know something like this should be possible based on this SO question that I found:
Laravel: How to use multiple pivot table relationships
My issue is this:
When I try to insert a relationship between a UserWebpage instance and a Collection instance, I get the following error.
Code to insert the relationship:
App\UserWebpage::where('user_id', $user->id)->take(2)->get()->each(function($user_webpage) use ($user){
$collection = factory(App\Collection::class)->create(['user_id' => $user_webpage->user_id]);
$collection->userWebpages()->attach($user_webpage->id);
});
The error I get:
Illuminate\Database\QueryException : SQLSTATE[42S22]: Column not
found: 1054 Unknown column '' in 'field list' (SQL: insert into
collection_user_webpage (``, collection_id) values (1, 1))
Is it possible to create this type of a relationship? Or am I missing something?

The default value for $foreignPivotKey doesn't work in Pivot, you have to explicitly specify it:
public function collections(){
return $this->belongsToMany('App\Collection', 'collection_user_webpage', 'user_webpage_id');
}

Related

Understanding Eloquent One-to-many Relationships

I'm trying to understand Eloquent relationships but it seems I'm missing something in understanding it. I have:
A Meeting produces many Documents.
A specific Document can be produced for one Meeting.
Thus a one to many relationship. I am trying to display the 'meeting_name' in the Document details table but get this error:
Trying to get property 'meeting_name' of non-object (View: C:\wamp64\www\yajra_contact_system\resources\views\documents\index.blade.php)
Here is my code.
Please please explain with code solution:
app\Document.php File:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Document extends Model
{
protected $fillable = [
'document_name',
'document_desc',
];
public function meeting(){
return $this->belongsTo(Meeting::class);
}
}
app\Meeting.php File:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Meeting extends Model
{
protected $fillable = [
'document_id',
'meeting_name',
'meeting_desc',
'room_no',
'no_of_invitees',
'comments'
];
public function documents(){
return $this->hasMany(Document::class);
}
}
app\Http\Controllers\DocumentsController.php File:
namespace App\Http\Controllers;
use App\Document;
use App\Meeting;
use Illuminate\Http\Request;
class DocumentsController extends Controller
{
public function index()
{
$documents = Document::all();
$meetings = Meeting::all();
return view('documents.index', compact('documents', 'meetings'));
}
}
resources\views\documents\index.blade.php File:
#foreach($documents as $document)
<tr>
<td>{{$document->id}}</td>
<td>{{$document->document_name}}</td>
<td>{{$document->document_desc}}</td>
<td>{{$document->meetings->meeting_name}}</td> <!-- ERROR IS HERE -->
</tr>
#endforeach
you have many problems in your code:
first: in order to use the relation ... you have to load it first ...
loading relation done by using with('relationName') method ...
in index:
$documents = Document::with('meeting')->all();
second:
<td>{{$document->meetings->meeting_name}}</td> <!-- ERROR IS HERE -->
the relation is named meeting without s .. not meetings ...
third:
it's pest practices to provide foreign key in relation:
in Meeting model
public function documents(){
return $this->hasMany(Document::class,'meeting_id');
}
in Document model:
public function meeting(){
return $this->belongsTo(Meeting::class,'meeting_id');
}
please make sure you have a column meeting_id in your documents table referenced as foreign key to id in meetings table
more details about loading relation in:
https://laravel.com/docs/7.x/eloquent-relationships#eager-loading
So you have your tables mixed up.
You have a single record per meeting yet you have a document_id in your meetings table which you would need to duplicate meeting record for each document.
Remove the document_id from your meetings table
Add a meeting_id to your documents table
remember to update your models fallible array else you wont get the new columns in the collection.
This should fix your problem as your relationships are correct.

I am trying to make Multi Level Category using laravel

I am trying to make Multi-Level Category using laravel but I am facing this error: How to fix this error?
Illuminate\Database\QueryException
SQLSTATE[42S02]: Base table or view
not found: 1146 Table 'storykadb.category_navmenus' doesn't exist
(SQL: select * from category_navmenus where p_id = 0)
Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class category_navmenu extends Model
{
public function childs(){
return $this->hasMany('App\category_navmenu','p_id');
}
}
Route
Route::get('test',function(){
return App\category_navmenu::with('childs')->where('p_id',0)->get();
});
Laravel Eloquent is taking the wrong table name, either you can change your Model name and table name according to Laravel's naming convention or add in the $table property in your model, like this :
namespace App;
use Illuminate\Database\Eloquent\Model;
class category_navmenu extends Model
{
public $table = "category_navmenu";
public function childs(){
return $this->hasMany('App\category_navmenu','p_id');
}
}
Because Laravel will find your table by changing your classname to lowercase underscore and plural. Just like:
CategoryNavmenu will become category_navemenus.
You have no specifies the table name of the protected $table. So laravel will find the table by default rule.
You can put this line in your model:
protected $table = 'category_navemenu';
so laravel can find your table.
But the important thing is plz change your class name to Upper Camel Case。This is a normal grammatical norms.
Just Change your model file name to CategoryNavmenu.php and classname to CategoryNavmenu.

Trying to get property of non-object Laravel hasMany Relation

I am pretty new to laravel and i am learning about relationships in eloquent. I have 3 models
Report
ReportModule
ReportSubModule
Relationships are such
SubModule hasMany Module
Report hasMany ReportModule
Report hasMany ReportSubModule
When i try to get the ReportSubModule from Report object in my view i have no error but when i try to get the ReportModule from Report object in my view i get error Trying to get property of non-object. If i print the ReportModule object i see json and i think i am getting the object but unable to get it's property
Here is my code
Report (Model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class Report extends Model
{
public function report_module(){
//module_id is column in reports table that corresponds to
//id column in report_modules table
return $this->belongsTo(ReportModule::class,'module_id');
}
public function sub_module(){
//sub_module_id is column in reports table that corresponds to
//id column in report_modules table
return $this->belongsTo(ReportSubModule::class,'sub_module_id');
}
}
ReportModule (Model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class ReportModule extends Model
{
public function subModules(){
return $this->hasMany(ReportSubModule::class);
}
public function reports(){
return $this->hasMany(Report::class);
}
}
ReportSubModule (Model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class ReportSubModule extends Model
{
public function module(){
return $this->belongsTo(ReportModule::class);
}
public function reports(){
return $this->hasMany(Report::class);
}
}
view
<h4> {{$report ->report_name}} </h4>
<small>{{ $report->sub_module->sub_module_name }} </small><br/><br/>
<?php
$m = $report->report_module;
<!-- i get error on below line -->
echo $m->module_name;
?>
What am i doing wrong here.I should be able to get the ReportModule object property just like ReportSubModule but i'm not.Please guide me to resolve this problem.
I assume you have the relationship like this -
Report id(primary key) -> ReportModule report_id(foreign key)
ReportModule id(primary key) -> ReportSubModule report_module_id(foreign key)
You will have the relation ship in each Model like below -
1) Report Model -
public function reportModule(){
return $this->hasMany(ReportModule::class,'report_id'); //you can use has one as well if required
}
2) Report Model -
//relationship with report table
public function module(){
return $this->belongsTo(Report::class,'report_id');
}
//relationship with report sub module
public function reportSubModule(){
return $this->hasMany(ReportSubModule::class,'report_module_id); // you can use has one if required
}
and so you can create the relationships..
hope it will work for you

hasOne relationship and associate()?

I have this relationship :
public function company(){
return $this->hasOne('App\Models\User','personal_users_business_users', 'user_id', 'business_user_id');
}
When i try this:
$user->company()->associate($business_user_id);
Im getting this error:
Call to undefined method
Illuminate\Database\Query\Builder::associate()
I have pivot table personal_users_business_users and it has user_id, business_user_id, approved
And now i want to insert in that pivot table business_user_id. What im doing wrong?
Your relationship should be like this:
public function company()
{
return $this->hasOne(User::class);
}
User is the model you want to connect with,
and you should call the relationship like this:
$user->company->business_user_id;
$user must be the Model you have the relationship function in.
company is the function and the business_user_id the field you want to get
associate() is a method of the belongsTo relationship, but it looks like from the above you are trying to call it via the hasOne relationship.
UPDATE
You can create a function in your App\Models\User class
public function company() {
return $this->belongsTo('MODEL_OF_COMPANY', 'foreign_key', 'owner_key', 'relation');
}
then call $this->company()->associate($company)

Base table or view not found: 1146 Table in laravel

I was creating one model file and trying to fetch the table data using this model.
Every time it's showing the error below:
"SQLSTATE[42S02]: Base table or view not found: 1146 Table
'laravel_student.students' doesn't exist (SQL: select * from
students)"
The controller file looks like to the following:
namespace project1\Http\Controllers;
use Illuminate\Http\Request;
use project1\Student;
use project1\Http\Requests;
class StudentController extends Controller
{
public function index()
{
$students = Student::all();
return view('student_form',compact('students'));
}
}
Open your Student Model
and add $table
class Student extends Model {
protected $table = 'student';
}
Follow Eloquent Defining Models for more details

Resources