one to one relationship in laravel (Error) - php

I am new in Laravel, when I practice I get an error.
at HandleExceptions->handleError('8', 'Trying to get property of non-object', 'C:\xampp\htdocs\cms\app\Http\routes.php', '144', array('id' => '1')) in routes.php line 144
my routes.php file
Route::get('/user/{id}/post',function ($id){
return User::find($id)->post->title;
});
in my User.php file
public function post(){
return $this->hasOne('App\Post');
}
I have two tables 1-posts 2-users
and I have also Post class
I also google and search different sites but can't understand.
Please me,how to rid this Error.

your posts are one user .
this renlship is "one-to-many" relationship .
you must for this reason using this method in modal user :
public function posts()
{
return $this->hasMany('App\Post');
}
one to many is array from posts .
for show resualt you must using foreach :
$comments = App\Post::find(1)->comments;
foreach ($comments as $comment) {
$comment->title ;
}
and reading this links : https://laravel.com/docs/5.2/eloquent-relationships#one-to-many

1:are you shure the relation is one to one;
2:if you shure add primary and foreign key and add this function in Post model.
public function user(){
return $this->hasOne('App\User','id','user_id');
}

Related

pass data to edit from the controller to the view in a many to many relationship

Hi everyone i have a many-to-many relationship between the turnos table and the dias table like this:
Currently, I'm doing the CRUD of the turnos table and for each turnos I have to assign many dias, I did it with the attach method.
Now the issue is in the edit method... how am I gonna get the assigned dias that is related to that turno so I can pass it to the view and the user can edit it?
If someone knows it please help me, I would appreciate it very much
//Dias Model
public function turnos()
{
return $this->belongsToMany(Turno::class);
}
//Turnos Model
public function dias()
{
return $this->belongsToMany(Dia::class);
}
// Controller
public function edit(Turno $turno)
{
// $dias = ??
return Inertia::render('Turnos/Editar', [
'turno' => $turno,
'dias' => ??
]);
}
The edit view Should looks like this:
You can load the relation with the load() method and just return the $turno variable that will contain the "turno" and the "dias".
public function edit(Turno $turno) {
$turno->load('dias');
return Inertia::render('Turnos/Editar', [
'turno' => $turno
]);
}
On the client side you can use v-model to fill your inputs.

laravel live-wire comment system N+1 problem Occur

I create the comment section and everything work fine but I have an n+1 problem and I quit don't know how to solve it I have Debug the application to check where the problem here What Happen
I am Creating an App like Instagram
First I load the post of the user and The one he follows In for each loop Here is the Query
$ids = Auth::user()->followings->pluck('id');
$ids->push( Auth::user()->id);
$posts= Post::with('user', 'comments', 'likers')->whereIn('user_id', $ids)->latest()->get();
return view('dashboard', [
'posts' =>$posts
'user' => Auth::user()
]);
For Each loop
I have Strip the Unnesserry Code
#foreach($posts as $post)
<livewire:comments :post="$post" />
#endforeach
So for Everything Work, Fine Here Occurs The Problem
Livewire Comment Component
public function mount($post)
{
$this->post = $post;
}
// This is the Method The Work Fine But I Want Pagination
public function render()
{
return view('livewire.comments', ['comments' => $this->post->comments]);
}
// and If I use The pagination I Ran Into n+1 Problem
public function render()
{
return view('livewire.comments', ['comments' => $this->post->comments()->paginate(5)]);
}
if You have Any Question I if you need I extra Information Just Tell Me ok
best Regards

What triggers the "Trying to get property of non-object" error

Since I started with my first Laravel project I've been having the error
Trying to get property 'column_name' of non-object nonstop, and most of the time I've been able to fix it one way or another, but the problem is, I have no idea of why I get the error, or how can I prevent it. For example,
// In my controller I have this domPDF function...
public function pdfgen(Request $request, $id) {
$data = Table::find($id);
View()->share('data', $data);
if ($request -> has('download')) {
$pdf = PDF::loadView('pdf/pdfgen');
return $pdf ->download('pdfgen.pdf');
}
return view('pdf/pdfgen');
}
// In my blade file I have a table calling this column...
<td>{{ $data->column }}</td>
// and this link making the request in the pdfgen function...
<a class="btn btn-primary" href="{{ route('pdfgen', ['download'=>'pdf']) }}">Download PDF</a>
// And in my routes of web.php...
Route::get('/pdfgen/{id}', array('as' => 'pdfgen', 'uses' => 'PDFController#pdfgen'));
and whenever I press that download link, I get a Whoops page with the trying to get property 'column' of non-object (View: /usr/src/workapp/resources/views/pdf/pdfgen.blade.php). Why am I getting this error and not the open/save dialog?
EDIT: Forgot to add, before trying to get specific data with $id, I called the whole table ($data = Table::all();) and used a #foreach in the blade view to print it in the table
EDIT 2: Adding the model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Table extends Model
{
protected $table = 'table';
protected $primaryKey = 'id';
public $incrementing = false;
protected $fillable = [
// all columns are strings, even id
'id',
'column',
'column2',
'column3',
];
public function table2()
{
return $this->hasMany('App\Table2');
}
}
When you do find($id) and the record is not present, it returns null. So if you try to access any property ->column, it will throw error.
You can either do findOrFail($id) or have condition if (is_null($data)) or on frontend have $data->column ?? 'defaultvalue
'
Now, the second situation where your model is present but you still get error, do :
$data = Table::find($id);
dd(array_keys($data->toArray()));
You should see the column you are trying to access if it is present.
Lastly, if it is not present in above step but is there in the table, then check for protected $hidden = [] setting of your model which essentially hides certain columns.
This happend because your $data might be null and your record with given $id might not exists in your database.
Try to change your code like below:
Table::findOrFail($id);
From now on if your table with given id doesn't exist, it'll automatically return 404 page.

Yii2 eager loading not working

I have two entities in my database which are related by a one to many relationship: "User" and "Ad"
I have generated model classes using gii.
This is what I have in my model class for User:
public function getAds()
{
return $this->hasMany(Ad::className(), ['user' => 'id']);
}
and for my Ad model:
public function getUser0()
{
return $this->hasOne(User::className(), ['id' => 'user']);
}
according to Yii2 documentation, In the controller when I do
$ads = Ad::find()->all();
var_dump($ads[0]->user);
It should eagerly load user data from the DB but I only get the foreign key (1).
Even when I try
$ads = Ad::find()->with('user0')->all();
var_dump($ads[0]->user);
Its still the same.
thanks. If I want to send Ads and their related user data by xml in an ActiveController, do I have to do something like this:
$t = array();
foreach ($ads as $ad) {
$t[] = [$ad, $ad->user0];
}
return $t;
Or there is a more straightforward way to do that?
You are still getting Ad objects either with or without eager loading.
The difference is how the relations are populated, with lazy loading the relations are only loaded when they are accessed.
$ads = Ad::find()->all();
foreach ($ads as $ad) {
var_dump($ad->user0); // query to load user record here
}
With eager loading they are populated up front.
$ads = Ad::find()->with('user0')->all();
foreach ($ads as $ad) {
var_dump($ad->user0); // user0 already populated, no query
}
Probably You need joinWith
$ads = Ad::find()->joinWith('user0')->all();

Yii - using afterDelete() to update data in another table

I am using Yii afterdelete() to update the related data which is deleted in another table. Here is my code in the controller:
Controller Action
public function actionDelete($id)
{
if(Yii::app()->request->isPostRequest)
{
// we only allow deletion via POST request
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
Model function
protected function afterDelete()
{
parent::afterDelete();
$show_model = new Show();
$show_model = Show::model()->findAll('tbl_season_id='.$this->id);
$show_model->updateAll('tbl_season_id = NULL, on_season=0');
}
As #Gregor said, a good use of active record relations would make the job much easier.
So, in Show model you would have something like:
public function relations()
{
return array(
'season' => array(self::BELONGS_TO, 'Season', 'tbl_season_id'),
);
}
While in Season model you would have something like:
public function relations()
{
return array(
'shows' => array(self::HAS_MANY, 'Show', 'tbl_show_id'),
);
}
Having relations defined, will give you the ability to do this:
public function afterDelete()
{
parent::afterDelete();
$season_shows = Season::model()->findByID($id)->shows; //using the shows relation
foreach($season_shows as $season_show) do
{
$season_show->setAttributes('tbl_season_id => NULL, on_season => 0');
$season_show->save();
}
}
Hummm, but if you noticed that second line in the afterDelete which calls findByID($id) but we are inside the afterDelete and the record is actually dead (deleted)!!
To fix this you can grab the id just before the model is deleted using a variable & abeforeDelete
//at the begining of your model class
$private = $cached_season_id;
...
//then somewhere at the end
...
public function beforeDelete()
{
$this->cached_tbl_season_id = $this->id;
return parent::beforeDelete();
}
Now if you change the id in the afterDelete to $this->cached_season_id .. it should work.
Well, this solution is based on this yii-fourm-topic and i am not quite sure if it's going to work as it is!! So, give it a try & let us know what happens?
That looks an awful lot like a HAS_MANY relationship from Season to Show, so you might want to use relations in the future to get related records. There is a pretty good documentation for that in the yii-guide: http://www.yiiframework.com/doc/guide/1.1/en/database.arr
It also seems to me, that you have a jQuery-background. You are calling updateAll on an array(which is returned by the findAll-function).
A proper updateAll-call might look like this:
Show::model()->updateAll(array("tbl_season_id"=>null, "on_season"=>0), "tbl_season_id = $this->id")
This would probably be even better with some kind of constraint but since that is imo a matter of taste, I'll leave it at that.

Categories