Reputation: 3
I designed form to save data in Laravel
and this problem shows me the following error
Property [id] does not exist on this collection instance.
This is my Code
Controller
public function create ()
{
$post = Post::all();
return view ("post.create",compact('post'));
}
view create.blade.php
<form action="{{url()->action ('PostController@store', ['id'=>$post->id])}}" method="POST">
<input type="text" name="title" placeholder="Write Title">
<input type="text" name="body" placeholder="Write Body">
<input type="submit" value="Submit" name="submit">
</form>
I know the problem is here, but I don't know what I can do
'PostController@store', ['id'=>$post->id])}}" method="POST"
Upvotes: 0
Views: 209
Reputation: 65
You can make it look cleaner for the route.
web.php
Route::post('/myform/store', 'PostController@store')->name('post.store');
In your view, you can use the route name you just created.
<form action="{{ route('post.store', ['id' => $post->id]) }}" method="post">
But since you don't have column of 'id' in your Post
then it returns the error you getting. Try creating a column 'id' first to resolve your problem.
I agree with @Watercayman on using model-binding instead, it's quick and makes the code more readable (and understandable too). Since Laravel quickly matches 'id' with unique id in the database. Take a look here for route parameters (how you can pass your data through URLs) and how to access your parameter here.
Using model binding will return you a collection.
public function store(Post $post)
Your $post
variable is a collection so if you want to access your 'id' column you will do $post->id
.
Upvotes: 1
Reputation: 91
This will return the collection
$post = Post::all();
Instead, pass one object to the view by using
$post = Post::first();
or if u want to check particular post or any other condition you can use where clause to it..
eg: $post = Post::where('id',$user_id)->first(); // It will return single row...It will solve your problem
Upvotes: 1
Reputation: 8178
The problem is that you are sending a collection of Post models to your view. The $post
variable contains a collection of Post models, which means that the collection will not have an id
because it is a collection, not a single Post.
This:
$post = Post::all();
returns a collection.
Because this is a create method, you may wish to new up a Post model:
$post = new Post();
and add a few things to it and save it before sending to the view to get an id
, OR, probably more useful: you can open the form without form-model binding since you don't actually have a Post model created yet -- just remove the ['id'=>$post->id]
part since there is no post
to have an id
at the time the form is created.
Upvotes: 1