Reputation: 1101
There is an error in Laravel 5.6 when I try to check is a model empty with isEmpty function.
Model:
namespace App\Models\Projectmanagement;
use Illuminate\Database\Eloquent\Model;
class Projects extends Model
{
protected $table = 'projects';
public $timestamps = false;
}
Controller:
public function create()
{
$project = new Projects;
return view('pages.projectmanagement.projects.edit', [
'project' => $project,
'companies' => Company::all(),
]);
}
View:
<form method="post">
{{ csrf_field() }}
@if($project->isEmpty())
@method('PUT')
@endif
</form>
The idea is that I reuse edit.blade view file for creating and updating data, so I need to check if a model is empty to make proper changes in the view file.
But in this case, Laravel 5.6 throws an error:
Method Illuminate\Database\Query\Builder::isEmpty does not exist. (View: /var/www/resources/views/pages/projects/edit.blade.php)
Upvotes: 3
Views: 5276
Reputation: 443
isEmpty() is not a valid function on your class.
did you mean to use the php function empty()?
In that case try the following:
<form method="post">
{{ csrf_field() }}
@if(empty($project))
@method('PUT')
@endif
</form>
Note that empty($project) is less optimised compared to $project === null.
Upvotes: 2
Reputation: 7083
Another way to get this is using Model
exists
variable.
For example:
//Case 1
$project = new Projects;
$project->exists; //Has false
//Case 2
$project = Projects::first();
$project->exists; //Has true
Ref: https://laravel.com/api/5.6/Illuminate/Database/Eloquent/Model.html
Upvotes: 7
Reputation: 1822
@if(!$project->id)
@method('PUT')
@endif
I am using forms the same way - one view for create and update, but not making difference in put/post. And using value="{{old('name', $item->name)}}" Check here for example: https://github.com/LaraModulus/admin-pages/tree/master/src
Upvotes: 1
Reputation: 545
Controller
Do this way
$project = Projects::all();
$project->isEmpty() will work
This you have init an object for the model not fetching records from model.
$project = new Projects;
Upvotes: 1