Reputation:
I'm building a simple project management web app and I have InnoDB as my tables engine and apparently I can't delete a "company" owning at least on project so I tried to handle the this case using appropriate error messages display.
My goal is to display tell the user that the company can't be deleted if the company has projects and I've succeeded doing that except that when I've deleted all the projects of that specific company from the database I still get the same message "Company has projects..."
*/
public function destroy(Company $company)
{
$current = Company::find($company->id);
if($current !== null){
$companiesProjects = $current->projects;
if($companiesProjects === null){
if($current->delete()){
return redirect()->route('companies.index')
->with('success', 'Company has been successfully deleted!');
}
}else{
return back()->withInput()->with('errors', 'Company has projects... it can\'t be deleted!');
}
}else{
return back()->withInput()->with('errors', 'Company does not exist!');
}
return back()->withInput()->with('errors', 'Company could not be deleted!');
}
}
I've tried another solution which is to use the Project object inside of the function after adding it's namespace to the resource controller but unluckily my php server stops running and my PC stops responding and I have no other choice but restarting PC
public function destroy(Company $company, Project $project)
{
$current = Company::find($company->id);
if($current !== null){
$companiesProjects = Project::where('company_id', $company->id);
if($companiesProjects === null){
/* if($current->delete()){
//return redirect()->route('companies.index')
//->with('success', 'Company has been successfully deleted!');
}*/
echo 'null';
}else{
//return back()->withInput()->with('errors', 'Company has projects... it can\'t be deleted!');
}
}else{
//return back()->withInput()->with('errors', 'Company does not exist!');
}
//return back()->withInput()->with('errors', 'Company could not be deleted!');
}
I'm only following a video course and I'm lost in the doc.
Upvotes: 1
Views: 68
Reputation: 9942
$company->projects
will return an array. Either a filled one or an empty one. But either way $company->projects === null
will return false.
You should just do:
if(!$current->projects->count()) {
// Empty
} else {
// Not empty
}
May I also interest you in some cleaner logic?
if ($company->projects->isNotEmpty()) {
return back()->withInput()->with('errors', 'Company has projects... it can\'t be deleted!');
}
if (!$company->delete()) {
return back()->withInput()->with('errors', 'Company could not be deleted!');
}
return redirect()->route('companies.index')
->with('success', 'Company has been successfully deleted!');
The $current = Company::find($company->id)
is unneeded. Since you're using model binding, the $company
will either be an instance alreaady, or the route will return a 404
, which also removes the need for the first if
block.
Upvotes: 1