Laravel 5.5 - Trying to get property of non-object - php

I am trying to update my data, but i keep getting this error message:
"Trying to get property of non-object (View: C:\xampp\htdocs\blog\resources\views\update.blade.php)".
This is my update.blade.php file
#extends ('layout')
#section ('title')
Update page
#stop
#section ('content')
<div class="row">
<div class="col-lg-12">
<form action="/todo/save" method="post">
{{ csrf_field() }}
<input type="text" class="form-control input-lg" name="todo"
value="{{ $todo->todo }}" placeholder="Type in to create a new todo">
</form>
</div>
</div>
<hr>
#foreach ($todo as $todo)
{{ $todo->todo }} <a href="{{ route('todo.update', ['id' =>$todo->id])
}}" class="btn btn-info btn-sm">Update</a> <a href="{{ route('todo.delete',
['id' =>$todo->id]) }}"class="btn btn-danger">Delete</a>
<hr>
#endforeach
#stop
my controller:
public function update($id){
//dd($id);
$todo = Todo::find($id);
return view('update')->with('todo', $todo);
}
and finally my update route:
Route::get('/todo/update/{id}', 'TodosController#update')-
>name('todo.update');
This is just some basic stuff, but im stuck in here for couple of hours now, and any help is highly appreciated!

Use findOrFail method on your controller to throw an Exception if $todo is empty
public function update($id){
$todo = Todo::findOrFail($id);
return view('update', compact('todo'));
}
The problem is also on your update.blade.php file. foreach $todo as todo, $todo has collection of eloquent model or eloquent model ? I think it's a eloquent model. So a loop doesnt have any sense.

That error would happen if todo were FALSE or some other non-object.
You can inspect it with a var_dump($todo);die(); in the controller.

find() will return either null or the model that is found. Assuming that the model is found, you're doing a for each on that model (foreach ($todo...)), which will iterate over the model's public properties. This is obviously not what you intend to do.
It looks to me like you're trying to loop over a list of your todos and print out edit/delete links. If this is the case, you need to get the list of your todos in your controller, pass it into your view, and fix your foreach statement.
Controller:
$todos = Todo::get();
// pass to view
View:
foreach ($todos as $todo)

Related

Livewire Laravel - TypeError: Cannot read property 'getAttributeNames' of null

I'm fetching data from Ajax after sending a form. There is a listener that is setting the attribute to my component.
What I'm trying to achieve is to display my results after having submitted the form.
In the component, the model has been well retrieved but when I would like to display it to my component, I get an error.
directive_manager.js:26 Uncaught (in promise) TypeError: Cannot read property 'getAttributeNames' of null
at _default.value (directive_manager.js:26)
at new _default (directive_manager.js:6)
at new DOMElement (dom_element.js:12)
at Function.value (dom.js:36)
at Component.get (index.js:56)
at Component.value (index.js:272)
at Component.value (index.js:246)
at Component.value (index.js:182)
at Component.value (index.js:158)
at Connection.value (index.js:30)
index.blade.php
<div id="results-products" class="results-products">
<livewire:charts-products>
</div>
....
<script>
...
var product= fetchData(url);
window.livewire.emit('set:product', product)
...
</script>
charts-products.blade.php
<div>
#isset($product)
#foreach ( $product->category as $category)
<div class="card">
<div class="card-header">
<h4>Product category</h4>
</div>
</div>
#endforeach
#endisset
</div>
ChartsProducts.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Product;
class ChartsProducts extends Component
{
public $products;
protected $listeners = [
'set:product' => 'setProduct'
];
public function render()
{
return view('livewire.charts-products');
}
public function setProduct($product)
{
$this->product= Product::find($product);
//I have checked and the assigned variable is ok
}
}
The products is a model and has a relationship Category.
Is there something that I missed ?
This has to do with the way the dom-differ inside Livewire behaves. Try adding a key to the loop item
<div>
#isset($product)
#foreach ($product->category as $category)
<div class="card" wire:key="{{ $loop->index }}">
<div class="card-header">
<h4>Product category</h4>
</div>
</div>
#endforeach
#endisset
</div>
See the troubleshooting in the docs https://laravel-livewire.com/docs/troubleshooting
Also, change your public property from $products to $product

Laravel records not geting as dynamic

views/show.blade.php
#extends('layouts.app')
#section('content')
<h5>Showing Task {{ $task->title }}</h5>
<div class="jumbotron text-center">
<p>
<strong>Task Title:</strong> {{ $task->title }}<br>
<strong>Description:</strong> {{ $task->description }}
</p>
</div>
#endsection
Controllers/HomeController.php
public function show(Task $task)
{
return view('show', compact('task', $task));
}
routes/web.php
Route::get('show/{id}', 'HomeController#show')->name('show');
views/viewalltask.blade.php
<td>{{$data->title}}</td>
No error / No Record / instead of particulr record display blank page
You need to change the route configuration to:
Route::get('show/{task}', 'HomeController#show')->name('show');
This way Laravel's IOC container knows how to resolve/bind it.
Must match the variable name used in the method definition:
public function show(Task $task)

Trying to delete record by CRUD route::delete method(Laravel 5.3)

I have a problem with Larave's framework program with deleting by CRUDS method DELETE.
My route method is:
Route::delete('cats/{cat}/delete', function(Furbook\Cat $cat){
$cat->delete(); return redirect('cats.index')
->withSuccess('Cat
has been deleted.'); });
My view with delete url:
#extends('layouts.master')
#section('header')
Back to the overview
<h2>
{{ $cat->name }}
</h2>
<a href="{{ url('cats/'.$cat->id.'/edit') }}">
<span class = "glyphicon glyphicon-edit"></span>
Edit
</a>
<a href ="{{ url('cats/'.$cat->id.'/delete') }}">
<span class ="glyphicon glyphicon-trash"></span>
Delete
</a>
<p>Last edited: {{ $cat->updated_at }}</p>
#endsection
#section('content')
<p>Date of Birth: {{ $cat->date_of_birth }} </p>
<p>
#if ($cat->breed)
Breed:
{{ url('cats/breeds/'.$cat->breed->name) }}
#endif
</p>
#endsection
My Cat model:
<?php
namespace Furbook;
use Illuminate\Database\Eloquent\Model;
class Cat extends Model {
// We specified the fields that are fillable in the Cat model beforehand
protected $fillable = ['name','date_of_birth','breed_id'];
// informacja o tym, żeby nie uaktualniać update_at w tabeli kotów
public $timestamps = false;
public function breed(){
return $this->belongsTo('Furbook\Breed');
}
}
?>
When I'm clicking on delete link, there is an error like this:
MethodNotAllowedHttpException in RouteCollection.php line 233:
I don't know what's wrong. Could you somoene help me with solving problem?
Could someone help me with this problem?
I would be very grateful, greetings.
This is to do with the Request you are making. You must either create form with the delete method like so
<form action="{{ url('cats/'.$cat->id.'/delete') }}" method="DELETE">
<button class ="glyphicon glyphicon-trash">Delete</button>
</form>
OR change your route to a get
Route::get('cats/{cat}/delete', function(Furbook\Cat $cat){
$cat->delete();
return redirect('cats.index')->withSuccess('Cat has been deleted.');
});
If you go the form route don't for get to add the {{ csrf_field() }}
https://laravel.com/docs/5.4/csrf
Using Route::delete(), you cannot place it in an anchor. Make a form with DELETE method.
{!! Form::model($cat, ['method' => 'DELETE', 'url' => 'cats/'.$cat->id.'/delete']) !!}
<button type="submit">Delete</a>
{!! Form::close() !!}

eloquent scope to eager load with constriant?

Ok so I'm trying to setup a scope that will restrict which users are returned based on a column in a hasOne relation.
Here are the two methods from my User model:
public function scopeHasImage($query)
{
return $query->with(['profile' => function($query){
$query->where('avatar', '!=', '');
}]);
}
public function profile()
{
return $this->hasOne('App\Profile');
}
When I call it like so:
$users = User::HasImage()->simplePaginate(15);
All of that works ok untill I go to display the code in my blade template like so:
#foreach($users as $user)
<div class="col-xs-12 col-sm-3 col-md-2">
<a href="{{ route('user.profile.public', ['id' => $user->id]) }}">
<img class="img-responsive" src="{{ $user->profile->avatar }}" />
</a>
</div>
#endforeach
That results in this error:
Trying to get property of non-object
I have dumped the $user->profile and it is an object which has attributes listed and one of those attributes is avatar. So I'm not sure why this is not working.
Any thoughts would be greatly appreciated.
Almost certainly one of your users has no profile attached. Because you probably dumped only the the first $user->profile you didn't see that...
You can fix this by wrapping it in an if:
#foreach($users as $user)
#if($profile = $user->profile)
<div class="col-xs-12 col-sm-3 col-md-2">
<a href="{{ route('user.profile.public', ['id' => $user->id]) }}">
<img class="img-responsive" src="{{ $profile->avatar }}" />
</a>
</div>
#endif
#endforeach
Or exclude users without a profile in the first place (which is probably what you wanted all along)
public function scopeHasImage($query)
{
return $query->with('profile')->whereHas('profile', function($query){
$query->where('avatar', '!=', '');
});
}

Trying to get a property of a non-object

I have the following snippet of code that should return the contents of a post.
My View:
#foreach($posts as $post)
<h2 class="post-title"> {{$post->title}} </h2>
<p> {{ $post->content_posts()->first()}} </p>
#endforeach
This return the ENTIRE object,
As soon as you only want the content (or any other attribute) part of the object it throws "Trying to get a property of a non-object" error
The View that has the error:
#foreach($posts as $post)
<h2 class="post-title"> {{$post->title}} </h2>
<p> {{ $post->content_posts()->first()->content}} </p>
#endforeach
The Controller looks as follows:
public function getAllPost(){
$posts = Post::all();
return View::make('posts.allposts', ['posts' => $posts]);}
The Model relationship are as follows:
This is the Post model:
public function content_posts(){
return $this-> hasMany('ContentPost');}
The ContentPost model:
public function post(){
return $this-> belongsTo('Post');}
Is there a mistake somewhere in my Model, Controller or in the View?
Try using;
$post->content_posts()->first()['content']
Make sure to check for the data $post->content_posts()->first() before you display what you want to prevent this error from occurring again.

Categories