Laravel 5, Trying to get property of non-object - laravel

My Controller :
public function show($id){
$user_id_1_connections = Connection::whereUser_id_1AndConnection_status($id, 1)->get();
$user_id_2_connections = Connection::whereUser_id_2AndConnection_status($id, 1)->get();
return view('connection.showConnection',['user_id_1_connections' => $user_id_1_connections, 'user_id_2_connections' => $user_id_2_connections]);
}
My Model :
protected $table = 'connections';
protected $fillable = ['user_id_1','user_id_2','connection_status'];
public function user()
{
return $this->belongsTo('App\User');
}
My Blade :
#foreach($user_id_1_connections as $user_id_1_connection)
{{ $user_id_1_connection->user->name }}
{{ $comment->user->name }}
#endforeach
#foreach($user_id_2_connections as $user_id_2_connection)
{{ $user_id_2_connection->user->name }}
#endforeach
I have made foreign key to user_id_1 and user_id_2 to users table.
$table->integer('user_id_1')->unsigned();
$table->foreign('user_id_1')->references('id')->on('users')->onDelete('cascade');
$table->integer('user_id_2')->unsigned();
$table->foreign('user_id_2')->references('id')->on('users')->onDelete('cascade');
But when I'm running this code. It's showing the error :
Trying to get property of non-object.

The problem here is probably that you don't have user assigned to each connection so instead of:
{{ $user_id_1_connection->user->name }}
you should write rather something like this:
{{ $user_id_1_connection->user ? $user_id_1_connection->user->name : 'unknown' }}
same in all other places when you use $x->y->z syntax. To display z you should make sure $x->y is not null

Related

laravel controller returns only 2 values

I have a database with 3 tables. A separate model is connected to each table, and there is a controller that accepts values from all models. On the site page, I will have 3 tables that will be populated from a mysql table.
When I connected 2 models, everything worked fine. But after connecting 3, I get an error
undefined variable: sec_3.
If you delete one of the variables, then everything will work fine. It seems to me that the problem is either with the controller or with the file blade.php but I do not know how to fix it so that everything works properly. How to fix it?
My code:
Controller:
class PreschoolInstitution3Controller extends Controller {
public function index(){
$context=['bbs' =>PreschoolInstitution3::latest()->get()];
$context_2=['s' =>PreschoolInstitution::latest()->get()];
$context_3=['sec_3' => TrainingPrograms::latest()->get()];
return view('our_employees', $context, $context_2, $context_3);
}
}
web.php:
Route::get('/OurEmployees',[PreschoolInstitution3Controller::class,'index'] )->name('OurEmployees');
blade.php:
#foreach ($s as $section_2) <tr> <td>{{$section_2->number}}<td> <td>{{$section_2->fullname }}<td> <td>{{$section_2->post }}<td> <td>{{$section_2->telephone }}</td> <td>{{$section_2->email }}</td>
#endforeach #foreach ($bbs as $section )
{{$section->number}} {{$section->full_name}} {{$section->post}} {{$section->education}} {{$section->category}} {{$section->teaching_experience}} {{$section->professional_development}}
#endforeach #foreach ($sec_3 as $section_3)
{{ $section_3->number }}
{{ $section_3->level }}
{{ $section_3->directions }}
{{ $section_3->type_of_educational_program }}
{{ $section_3->period_of_assimilation }}
{{ $section_3->number_of_students }}
#endforeach
You should pass an array of data to view:
class PreschoolInstitution3Controller extends Controller {
public function index(){
$context = [
'bbs' => PreschoolInstitution3::latest()->get(),
's' => PreschoolInstitution::latest()->get(),
'sec_3' => TrainingPrograms::latest()->get()
];
return view('our_employees', $context);
}
}
https://laravel.com/docs/9.x/views#passing-data-to-views
Another one is that add a second parameter of an array with name to view( ) .
class PreschoolInstitution3Controller extends Controller {
public function index(){
$bbs = PreschoolInstitution3::latest()->get();
$s = PreschoolInstitution::latest()->get();
$sec_3 = TrainingPrograms::latest()->get();
return view('our_employees', [
'bbs' => $bbs,
's' => $s,
'sec_3' => $sec_3
]);
}
}

foreach() argument must be of type array | object, null given (Laravel Livewire)

This code is working fine
public function render(){
$this->products = ProductModel::get();
return view('livewire.product');
}
But when I am trying to paginate using laravel livewire, it gives me an error
public function render(){
return view('livewire.product', [
'products' => ProductModel::paginate(10)
]);
}
Blade File
#foreach ($products as $product)
{{ $product->name }}
{{ $product->price }}
#endforeach
#if(!empty($products))
{{ $products->links() }}
#endif
import this in Component
use Livewire\WithPagination;
class Product extends Component
{
use WithPagination;
....
}
and add in view
#if(!empty($products))
{{ $products->links() }}
#endif
Ohh I got it.Actually I have already use $products variable as a global variable
and when I change $products to other name it works.
Thanks alot...

larvel blade templates and elequent models -- how to get first element in many relationship

I have the following eloquent models (removed code to make it simple for this problem). I am trying to get the first image
class Design extends Model
{
use SoftDeletes;
protected $guarded = ['id','tags','keywords'];
public function images()
{
return $this->hasMany(DesignImage::class);
}
...
}
class DesignImage extends Model
{
use SoftDeletes;
public function design()
{
return $this->belongsTo(Design::class);
}
}
Then I have the following code that gets passed to a blade template
$data['designs'] = Design::where('quantity','>',0)->get();
return view('mailings.form',$data);
Template (Works fine; I get the name of all images
#foreach($design->images as $image)
{{ $image->name }}
#endforeach
But if I try
{{ $design->images->first()->name }}
I get Trying to get property 'name' of non-object`
If I try
{{ $design->images[0]->name }}
I get Undefined offset: 0
However if I do
#json ($design->images->first())
I get (valid)
{"id":1,"name":"Image 1 Design 1","thumb":"images/main_thumb.jpg","image":"images/main_large.jpg","design_id":1,"created_at":"2018-12-11 20:10:03","updated_at":"2018-12-11 20:10:03","deleted_at":null}
How do I get the first image in a blade template? Why am I getting this odd output?
Error occurs because latest one $design does not have image. Try this code
#foreach($designs as $design)
// your code
#php
$firstImage = $design->images()->first();
#endphp
{{ !empty($firstImage->name) ? $firstImage->name : ''}}
// other part ofcode
#endforeach
Also you can optimize this code using in controller
$data['designs'] = Design::where('quantity','>',0)->with('images')->get();
return view('mailings.form',$data);
In view
#foreach($designs as $design)
// your code
#php
$firstImage = $design->images->first();
#endphp
{{ !empty($firstImage->name) ? $firstImage->name : ''}}
// other part ofcode
#endforeach

Laravel revisionable getting a list of all revisions by specific user

I'm using the VentureCraft/revisionable-package and it shows me in the ReadMe how to show the Revisions of a Model that has revisions:
#foreach($account->revisionHistory as $history )
<li>
{{ $history->userResponsible()->first_name }}
changed {{ $history->fieldName() }}
from {{ $history->oldValue() }}
to {{ $history->newValue() }}
</li>
#endforeach
But I want a list of All revisions that are done by a Specific user; how to achieve that? So I can show a History of Revisions that are done by one specific user.
I have never used this package. But based on what I see, you should be able to add this in your User model
public function revisions()
{
return $this->hasMany(\Venturecraft\Revisionable\Revision::class)
}
then
#foreach($user->revisions as $history )
<li>
{{ $user->first_name }}
changed {{ $history->fieldName() }}
from {{ $history->oldValue() }}
to {{ $history->newValue() }}
</li>
#endforeach
As you asked in the comments :
But I'm missing the Entity that's changed in that list.
(optional) I would implement an interface to my revisionable models with something like :
<?php
namespace App\Contracts;
interface RevisionableContract {
public function entityName();
}
Then in all my models that use the RevisionableTrait :
<?php
namespace App\Models;
class MyModel extend Eloquent implements RevisionableContract {
use RevisionableTrait;
// (required)
public function entityName(){
return 'My Entity name';
}
}
Finally :
#foreach($user->revisions as $history )
<li>
{{ $user->first_name }}
changed {{ $history->fieldName() }}
from {{ $history->oldValue() }}
to {{ $history->newValue() }}
on the entity {{ $history->historyOf()->entityName() }}
</li>
#endforeach
historyOf() may return false
Do you also have an idea how I can make a list of all revisions in desc-order with that info of the user?
From the migrations file, I can see that it has created_at and updated_at timestamps.
You have two possibilities :
In your view, you can directly order them on your collection like this :
#foreach($user->revisions->sortByDesc('created_at') as $history )
When you get a lot of revisions for a user, you will probably have performance issues and you will have to paginate them. From your controller, you will have to sort them and paginate them in your query instead of the collection.
public function index()
{
$user = User::find(1);
$revisions = $user->revisions()->orderBy('created_at')->paginate(15);
return view('your.view', compact('user', 'revisions'));
}
I could not use that package but it seems quite easy to understand. If you can show history of a user you should add this to your "User" entity:
public function history()
{
return $this->hasMany(\Venturecraft\Revisionable\Revision::class, 'user_id', 'id');
}
Or if you want to filter a specific morphable entity you should do it like this:
public function historyForUser(User $user)
{
return $this->morphMany(\Venturecraft\Revisionable\Revision::class, 'revisionable')->where('user_id' , '=', $user->getKey())->getResults();
}
I think that answer is corresponded for what you want to do.

Laravel 5.5 - Save multiple data continiously from blade

I want to make a PHP method using laravel. I want to do the comparison of criteria and criteria. Here is the controller code :
public function create()
{
$kriteria1 = Model\Kriteria::pluck('nama_kriteria', 'id');
$kriteria2 = Model\Kriteria::pluck('nama_kriteria', 'id');
return view('kriteria_kriterias.create')->with('kriteria1', $kriteria1)->with('kriteria2', $kriteria2)->with('data', $data);
}
and this is the blade code :
It will make the form appear as total of criteria#
The problem is, I can't save it all to database. How do I get it to do this?
Updated method in the controller to the following:
public function create()
{
$kriteria1 = Model\Kriteria::pluck('nama_kriteria', 'id');
$kriteria2 = Model\Kriteria::pluck('nama_kriteria', 'id');
$data = [
'kriteria1' => $kriteria1,
'kriteria2' => $kriteria2
];
return view('kriteria_kriterias.create')->with($data);
}
How to output in the blade file:
{{ $kriteria1 }}
{{ $kriteria2 }}
Or you update the controller to pass the complete results:
public function create($id1, $id2)
{
$kriteria1 = Model\Kriteria::find($id1);
$kriteria2 = Model\Kriteria::find($id2);
$data = [
'kriteria1' => $kriteria1,
'kriteria2' => $kriteria2
];
return view('kriteria_kriterias.create')->with($data);
}
And the in the blade you can accss the data in various ways, one way is a foreach loop using blade in the blade template:
#foreach($kriteria1 as $k1)
{{ $k1 }}
#endforeach
#foreach($kriteria2 as $k2)
{{ $k2 }}
#endforeach'
To accept multiple values dynamicaly in the controller you can try something like this:
public function create($ids)
{
$results = collect([]);
foreach($ids as $id) {
$kriteria = Model\Kriteria::findOrFail($id);
if($kriteria) {
$results->put('kriteria' . $id, $kriteria);
}
}
return view('kriteria_kriterias.create')->with($results);
}
Then use the same looping method mentioned above to display them in the blade or a for loop that gets the count and displays accordingly.
maybe you forgot to add the opening tag ;)
{!! Form::open(array('url' => 'foo/bar')) !!}
//put your code in here (line 1-34)
{!! Form::close() !!}

Resources