Attempt to read property "id" on null - description.blade.php - php

I have a problem with id
i get error
Attempt to read property "id" on null (View: /resources/views/admin/Attendance/description.blade.php)
view code that show error
<form method="post" action="{{route('time.outd',['id'=>$attend->id])}}" enctype="multipart/form-data" >
controller code:
public function outd(Request $request, $id)
{
$request->validate([
'out'=>'',
'description'=>'required',
]);
$attend=Attendance::where('employee_id',$id)->orderBy('id','desc')->first();
$attend->description=$request->get('description');
$attend->update([
'out' => Carbon::now()
]);
$attend->save();
return redirect()->route('time.index')->with('success', ' success.');
}

I think you're just a little off here. '$attend->id you are setting the id to a null value because you haven't set it. From the controller that is passing the view of this form you need to pass that id to the front. So your collection of $attend is available on the front. Should be something like this in your controller action.
return view('index', compact('attend'));
Then in your form action just post to a non wildcard route...
action="{{route('time.outd')}}"
Then in your form elements put...
<input type="hidden" name="id" value="{{$attend->id}}">
Then in your controller where this is being posted to your id will be...
$request->id
Now you know if it is null on the back-end post that there was no record from the model and that you need to create a new one. If it has an id then you can go on about your day processing.

Related

'pic_name' field doesn't have a default value Laravel

so im trying to insert the name of picture into Mysql DB but after i submit the form it gives me a error of 'pic_name' field doesn't have a default value... that means my controller is not storing value of form
here is my blade :
<div>
<form action="/product_store" method="post" enctype="multipart/form-data">
#csrf
<input type="text" name="name_product">
<input type="file" name="file_product">
<button type="submit">submit</button>
</form>
</div>
and controller:
public function store(Request $request)
{
$original_name= $request->file('file_product')->getClientOriginalName();
$path = $request->file('file_product')->store('storage');
Product::create(['name' => $request['name_product'], 'pic_name' => $original_name]);
}
name field is storing perfectly so there is no problem with my web.php
Make pic_name fillable in model.
class Product extends Model
{
protected $fillable = [
'name', 'pic_name'
];
}
Note : sometimes what happened in your table that feild value is not set for default or not null. so while inserting data you don't get that value to insert in that case you need to make as default null.
Table-> feild -> make it null
-> make null if you don't want to store value while insert

Property [id] does not exist on this collection in Form

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"
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
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.
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.

Laravel 5.6 return request data if validation fails issue

I want to return back request data into fields if validation fails on create action.
I've created resource controller and there is pre-set functions (index, create, store, show, edit, update, destroy).
In example, in the Edit controller I already have an ID of a record, then I can just select record from DB by it's ID and pass it's data to the view, so that I will able to see entry data in fields on page load:
<input name="name" value="{{ $name }}" />
public function edit($id)
{
$item = Item::find($id);
return view('pages.item.edit')->with($data);
}
But in the Create controller I do not have any ID of item to fetch and pass entry data for fields.
<input name="name" value="{{ old('name') }}" />
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|string|max:30'
])->withInput();
return redirect('/items')->with('success', 'New item created!');
}
Should I use ->withInput() and where? {{ old('name') }} doesn't work too.
This and this articles didn't help me
So, how to save fields if validation fails? For Edit method it will be also useful to save modified fields.

Laravel: How to use the ignore rule in Form Request Validation

Laravel has a 'unique' rule with an 'except' clause. From the validation documentation, it takes this form:
unique:table,column,except,idColumn
My application has a 'shop' entity. When the user updates the shop's profile, I have a Form Request, with a validation rule configured as follows:
public function rules()
{
return [
'shop.name' => 'required|string|max:100|unique:shops,name,except,id',
];
}
(The primary key on my shops table is id).
The problem is that Laravel does not take any notice of the 'except' clause. This makes sense (sort of) since the shop ID is not being injected into the Form Request. I can inject id as just another form value, but that doesn't seem to work.
How can I get this rule working in a Form Request?
To use the except clause of the unique rule, we need to provide the value of the field on the record that we want the rule to ignore directly in the rule itself.
So, if we want a unique name field for every record except for on the record that the request updates, we need to add the value of the ID field to ignore:
class UpdateShopRequest extends FormRequest
{
...
public function rules()
{
return [
'shop.name' => 'unique:shops,name,' . $this->shop['id'],
];
}
}
As shown, this rule will cause validation to fail if any row contains the same shop name unless the row's id matches $this->shop['id']. This example assumes that our form contains a nested input field for the record's ID attribute because this particular question is performing validation on an array input:
<input type="hidden" name="shop[id]" value="{{ $shop->id }}">
...which lets us fetch the value within the request like we can with any other request.
However, most forms do not contain arrays, so—in other cases—the validation rule will likely refer to the input field directly (without nested identifiers):
'name' => 'unique:shops,name,' . $this->id,
More typically, we pass the record ID as a route parameter, which we can retrieve using the request's route() method:
'name' => 'unique:shops,name,' . $this->route('id'),
...which works if we have a route defined similarly to:
Route::post('shops/{id}', ...);
The fourth parameter to the unique validation rule lets us specify which column the except clause applies to, and defaults to id, so we can leave it off if we're just comparing the record's ID.
The rule looks a bit clumsy when we just concatenate the column value, especially for a field with a lot of other rules. Since version 5.3, Laravel provides a more elegant syntax to create a unique rule with an except clause:
use Illuminate\Validation\Rule;
...
return [
'name' => [
'required',
'string',
'max:100',
Rule::unique('shops', 'name')->ignore($this->id, 'optional_column'),
],
];
This example assumes that our form contains an array input field for the record's ID attribute because the question is performing validation on an array input:
<input type="hidden" name="shop[id]" value="{{ $shop->id }}">
Laravel 5.8: I've tried you solution right now, without adding the input, it's working well. Because Laravel pass the Shop object into request (shown with dd() into rules() )
Just:
`public function rules()
{
return [
'name' => 'unique:shops,name,'.$this->shop->id
];
}`
I use this solution in laravel 9, assuming that you use route model binding and resource controller, and do not have to add hidden input for the model id.
public function rules()
{
return [
'buy' => 'required|numeric|gt:0',
'sell' => 'required|numeric|gt:0',
'date' => 'required|' . Rule::unique('prices')->ignore($this->price),
];
}
for laravel 8 use $this->get('id') to exclude current record to taste
use Illuminate\Foundation\Http\FormRequest;
class Update extends FormRequest
{
public function rules()
{
return [
'name' => ['required', 'string', 'unique:shops,slug,'. $this->get('id')],
];
}
}

Laravel 5.1 Delete a row from database

I am trying to delete a category by clicking on a button
Blade:
<td class="center"><span class="glyphicon glyphicon-trash"></span></td>
Route:
Route::get('/deletecat/{name}','CategoryController#delete');
Controller:
public function delete($name)
{
category::find($name)->delete();
return Redirect::route('managecategory');
}
but I am getting an error while clicking on a button that
Call to a member function delete() on a non-object
Any help appreciated.
The ::find($id) method expects $id to be a number, the primary key of the row you want to find.
If you want to delete a row by name, you should use the following code:
category::where('name', $name)->delete();
The error is obviously because of the returned NON-OBJECT.
::find($name) returns an empty object or null
This is because the search was empty.
Make sure name is the primary key in order to use find.
Otherwise:
use ::where('name', $name)->delete();
or:
::where('name','=', $name)->delete();
*I pointed = because if you ever need to search different than = use >= <> and so on...
Secondly, it is not very important to use destroy. It is recommended but not a must-have!
In your view:
it has to be a form to submit a POST request like below:
<form action="/deletecat/{{$data->id}}" method="post">
#csrf
#method('DELETE')
<input type="submit" value="delete " >
</form>
Because this is POST Request has to use csrf and delete action.
In your route, it has be with delete() method,followwing with the controller.
Route::delete('/deletecat/{name}', 'CategoryController#destory');
In the controller:
public function destory($name)
{
category::find($name)->delete();
return Redirect::route('managecategory');
}
This is how laravel name format role:

Categories