I have a simple CRUD app with two main models: Manufacturers (representing companies), and Devices (representing products made by those companies). Each device is assigned to one manufacturer – that is, there is a one-Manufacturer-to-many-Devices relationship.
When the user tries to delete a Manufacturer, I want my app to prevent that deletion if there are any Devices assigned to it. I have this part working. In my Manufacturer.php model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Device;
class Manufacturer extends Model {
protected static function boot() {
parent::boot();
static::deleting( function( $manufacturer ) {
// If there are devices assigned to this manufacturer, prevent the
// deletion
$device = Device::where( 'manufacturer_id', $manufacturer->id )->first();
if ( $device ) {
return false;
}
} );
}
}
And in my controller:
public function destroy( $id ) {
$manufacturer = Manufacturer::findOrFail( $id );
if ( !$manufacturer->delete() ) {
return redirect( route('admin.manufacturers.edit') )->with( 'message', 'Couldn\'t delete manufacturer!' );
}
return redirect( route('admin.manufacturers.index') )->with( 'message', 'Manufacturer deleted.' );
}
My question: it possible for the deleting() handler to tell the controller why the deletion was prevented?
In the example above, there's only one reason – but in a real application, there could be any number of reasons that $manufacturer->delete() might return false. Maybe the Manufacturer was locked by an administrator. Maybe the user doesn't have the right permissions. Maybe it was just a database hiccup. I'd like to display something more informative than "Couldn't delete manufacturer".
I'm open to totally different approaches to handling model events, as well (for cases like this, and things such as delete cascades). I'm just learning my way around Laravel events, and there's to be a lot of conflicting information out there – it seems like this part of the API may have been in rapid flux throughout the 5.x versions, and Laravel 5.2 is only six months old. So it's hard to find reliable info.
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/20qWqfF
via IFTTT
Aucun commentaire:
Enregistrer un commentaire