我有以下表格:
{
Schema::create('properties', function (Blueprint $table) {
$table->increments('id');
$table->string('property_name');
$table->integer('category_id');
$table->timestamps();
});
}
和
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
我注册了一个带有类别ID的房产。之后,我删除了表类别中的一个类别,并收到以下消息:
(1/2) ErrorException
Trying to get property of non-object
Trying to get property of non-object (View: C:\laragon\www\PRO\resources\views\properties\index.blade.php)
当我尝试查看属性时出现消息,因为已连接到它们的类别ID 不再存在。
建议的代码插入后,我收到以下错误消息:
(1/1) FatalThrowableError
Class 'App\CategoryDeleted' not found
in HasEvents.php (line 165)
at Model->fireCustomModelEvent('deleted', 'fire')
in HasEvents.php (line 140)
at Model->fireModelEvent('deleted', false)
in Model.php (line 754)
at Model->delete()
in CategoryController.php (line 114)
at CategoryController->destroy('3')
at call_user_func_array(array(object(CategoryController), 'destroy'), array('category' => '3'))
in Controller.php (line 55)
at Controller->callAction('destroy', array('category' => '3'))
in ControllerDispatcher.php (line 44)
at ControllerDispatcher->dispatch(object(Route), object(CategoryController), 'destroy')
in Route.php (line 203)
这是我的类别控制器:
命名空间App \ Http \ Controllers;
use Illuminate\Http\Request;
use App\Property;
use App\Category;
use Session;
use App\Events\CategoryDeleted;
class CategoryController extends Controller
{
public function __construct()
{
$this->middleware(['auth', 'admin']);
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//indexing the categories from the database
$categories = Category::orderBy('id', 'desc')->paginate(100000);
//return a view and pass the above variable
return view('categories.index')->withCategories($categories);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//Showing the registratin form for the cities
return view('categories.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//Seve a new category
$this->validate($request, array(
'name' => 'unique:categories|max:255'
));
$category = new Category;
$category->name = $request->name;
$category->save();
Session::flash('success', 'A new Category has been successfully saved!');
return redirect()->route('categories.index');
}
/**
*
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
// find the category in the database and save as a var
$category = Category::find($id);
// return the view and pass in the var we previously created
return view('categories.edit')->withCategory($category);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$category = Category::find($id);
// Validate the data
$this->validate($request, array(
'name' => 'unique:categories|max:255'
));
$category = Category::find($id);
$category->name = $request->input('name');
// Save the data to the database
$category->save();
Session::flash('success', 'A new Category has been successfully updated!');
// redirect with flash data to cities index
return redirect()->route('categories.index');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$category = Category::find($id);
$category->delete();
Session::flash('success', 'The category was successfully deleted.');
return redirect()->route('categories.index');
}
}
这是建议的代码: https://stackoverflow.com/a/45190713/7705605
请记住表名是属性而不是产品,我已在建议的代码中进行了更改。我的意思是改变产品一词的属性。再次感谢你!
这是我的事件放在app \ events中,名为CategoryDeleted.php 看起来像这样:
<?php
namespace App\Events;
use App\Category;
use Illuminate\Queue\SerializesModels;
/**
* Class CategoryDeleted
* @package App\Events
*/
class CategoryDeleted
{
use SerializesModels;
/**
* @var Category
*/
public $category;
/**
* Create a new event instance.
*
* @param Category $category
*/
public function __construct(Category $category)
{
$this->category = $category;
}
}
这是我的听众放在听众中并命名 DissociatePropertiesFromDeletedCategory.php:
namespace App\Listeners;
use App\Events\CategoryDeleted;
// use Illuminate\Queue\InteractsWithQueue;
// use Illuminate\Contracts\Queue\ShouldQueue;
class DissociatePropertiesFromDeletedCategory
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param CategoryDeleted $event
* @return void
*/
public function handle(CategoryDeleted $event)
{
$event->category->properties()->update(['category_id' => null]);
}
}
这是EventServiceProvider.php:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'App\Events\RegistrationCompleted' => [
'App\Listeners\SendRegistrationEmail',
],
'App\Events\CategoryDeleted' => [
'App\Listeners\DissociatePropertiesFromDeletedCategory',
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
//
}
}
这是我的分类模型:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
public function properties ()
{
return $this->hasMany('App\Property');
}
protected $events = [
'deleted' => CategoryDeleted::class,
];
}
这是我的物业模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Property extends Model
{
//Category
public function category ()
{
return $this->belongsTo('App\Category');
}
//City
public function city ()
{
return $this->belongsTo('App\City');
}
//Country
public function country ()
{
return $this->belongsTo('App\Country');
}
//Tag
public function tags()
{
return $this->belongsToMany('App\Tag');
}
//Appraiser
//Tag
public function appraiser()
{
return $this->belongsTo('App\Appraiser');
}
}
这可能是propertyController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Property;
use Session;
use App\City;
use App\Country;
use App\Category;
use App\Appraiser;
class PropertyController extends Controller
{
public function __construct()
{
$this->middleware(['auth', 'admin']);
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//create and index the properties from the database
$properties = Property::orderBy('id', 'desc')->paginate(100000);
//return a view and pass the above variable
return view('properties.index')->withProperties($properties);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//Call all categories/cities/coutries/tags and everything else to show them in the form
$categories = Category::all();
$cities = City::all();
$countries = Country::all();
$appraisers = Appraiser::all();
// $tags = Tag::all();
return view('properties.create')->withCategories($categories)->withCities($cities)->withCountries($countries)->withAppraisers($appraisers);
// ->withTags($tags);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// dd($request);
$this->validate($request, [
//Location
'address' => 'required|max:255',
'city_id' => 'required|integer',
'country_id' => 'required|integer',
'category_id' => 'required|integer',
'website' => 'nullable|url',
'slug' => 'required|alpha_dash|min:5|max:155|unique:properties,slug',
// 'image' =>'nullable|image',
'comment' => 'nullable|max:255',
//Financial
'price_paid' => 'required|integer',
'loan_ltv' => 'required|integer',
'rent' => 'required|integer',
'mortgage' => 'required|integer',
'management_moe' => 'required|integer',
'o_fees' => 'required|integer',
'contingencies' => 'nullable|integer',
'diligence' => 'nullable|integer',
'letting_agent_fees'=> 'nullable|integer',
//Contact
'appraiser_id' => 'nullable|integer',
]);
//store in the database
$property = new Property;
//Location
$property->address = $request->address;
$property->city_id = $request->city_id;
$property->country_id = $request->country_id;
$property->category_id = $request->category_id;
$property->website = $request->website;
$property->slug = $request->slug;
// $property->image =$request->image;
$property->comment = $request->comment;
//Financial
$property->price_paid = $request->price_paid;
$property->loan_ltv = $request->loan_ltv;
$property->rent = $request->rent;
$property->mortgage = $request->mortgage;
$property->management_moe = $request->management_moe;
$property->o_fees = $request->o_fees;
$property->contingencies = $request->contingencies;
$property->diligence = $request->diligence;
$property->letting_agent_fees = $request->letting_agent_fees;
//Contacts
$property->appraiser_id = $request->appraiser_id;
//store in the database
$property->save();
// $property->tags()->sync($request->tags, false);
//Flash session informing the data was successfully save
Session::flash('success', 'The property project was successfully saved!');
//redirect to the page you want
return redirect()->route('properties.show', $property->id);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show(Property $property)
{
return view('properties.show')->withProperty($property);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit(Property $property)
{
//Category
$categories = Category::all();
$cats = array();
foreach ($categories as $category) {
$cats[$category->id] = $category->name;
}
//City
$cities = City::all();
$home = array();
foreach ($cities as $city) {
$home[$city->id] = $city->name;
}
//Country
$countries = Country::all();
$place = array();
foreach ($countries as $country) {
$place[$country->id] = $country->name;
}
//Appraiser
$appraisers = Appraiser::all();
$apprai = array();
foreach ($appraisers as $appraiser) {
$apprai[$appraiser->id] = $appraiser->first_name;
}
// $tags = Tag::all();
return view('properties.edit')->withProperty($property)->withCategories($cats)->withCities($home)->withCountries($place)->withAppraisers($apprai);
// ->withTags($tags);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$property = Property::find($id);
if ($request->input('slug')== $property->slug) {
$this->validate($request, array(
//Location
'address' => 'required|max:255',
'city_id' => 'required|integer',
'country_id' => 'required|integer',
'category_id' => 'required|integer',
'website' => 'nullable|url',
// 'slug' => 'required|alpha_dash|min:5|max:155|unique:properties,slug',
// 'image' =>'nullable|image',
'comment' => 'nullable|max:255',
//Financial
'price_paid' => 'required|integer',
'loan_ltv' => 'required|integer',
'rent' => 'required|integer',
'mortgage' => 'required|integer',
'management_moe' => 'required|integer',
'o_fees' => 'required|integer',
'contingencies' => 'nullable|integer',
'diligence' => 'nullable|integer',
'letting_agent_fees'=> 'nullable|integer',
//Contact
'appraiser_id' => 'nullable|integer',
));
} else {
$this->validate($request, array(
//Location
'address' => 'required|max:255',
'city_id' => 'required|integer',
'country_id' => 'required|integer',
'category_id' => 'required|integer',
'website' => 'nullable|url',
'slug' => 'required|alpha_dash|min:5|max:155|unique:properties,slug',
// 'image' =>'nullable|image',
'comment' => 'nullable|max:255',
//Financial
'price_paid' => 'required|integer',
'loan_ltv' => 'required|integer',
'rent' => 'required|integer',
'mortgage' => 'required|integer',
'management_moe' => 'required|integer',
'o_fees' => 'required|integer',
'contingencies' => 'nullable|integer',
'diligence' => 'nullable|integer',
'letting_agent_fees'=> 'nullable|integer',
//Contact
'appraiser_id' => 'nullable|integer',
));
}
//store in the database
$property->address = $request->input('address');
$property->city_id = $request->input('city_id');
$property->country_id = $request->input('country_id');
$property->category_id = $request->input('category_id');
$property->website = $request->input('website');
$property->slug = $request->input('slug');
// $property->image =$request->input('image');
$property->comment = $request->input('comment');
//Financial
$property->price_paid = $request->input('price_paid');
$property->loan_ltv = $request->input('loan_ltv');
$property->rent = $request->input('rent');
$property->mortgage = $request->input('mortgage');
$property->management_moe = $request->input('management_moe');
$property->o_fees = $request->input('o_fees');
$property->contingencies = $request->input('contingencies');
$property->diligence = $request->input('diligence');
$property->letting_agent_fees = $request->input('letting_agent_fees');
$property->category_id =$request->input('category_id');
$property->city_id =$request->input('city_id');
$property->country_id =$request->input('country_id');
$property->appraiser_id =$request->input('appraiser_id');
$property->save();
Session::flash('success', 'The property project was successfully updated!');
return redirect()->route('properties.show', $property->id);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$property = Property::find($id);
// $pos->tags()->detach();
$property->category()->detach();
$property->city()->detach();
$property->country()->detach();
$property->delete();
Session::flash('success', 'The project was successfully deleted.');
return redirect()->route('properties.index');
}
}
这是我的index.blade.php:
@section('content')
</section>
<!-- Main content -->
<section class="content">
@include('layouts.admin-partials.messages')
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-header">
<h3 class="box-title">Data Table With Full Features</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>#</th>
<th>Address</th>
<th>City</th>
<th>Country</th>
<th>Category</th>
<th>Price</th>
<th>Loan</th>
<th>Rent</th>
<th>Mortgage</th>
<th>Manage</th>
<th>Other Fees.</th>
<th>Contingencies</th>
<th>Diligencies</th>
<th> View</th>
</tr>
</thead>
<tbody>
@foreach ($properties as $property)
<tr>
<td>{{ $property->id }}</td>
<td>
<a>{{ $property->address }}</a>
<br />
<small>{{ date('M j, Y h:ia', strtotime($property->created_at)) }}</small>
</td>
<td>{{ $property->city->name }} </td>
<td> {{ $property->country->name }}</td>
<td> {{ $property->category->name }}</td>
<td> {{ $property->price_paid }}</td>
<td> {{ $property->loan_ltv }}</td>
<td> {{ $property->rent }}</td>
<td> {{ $property->mortgage }}</td>
<td> {{ $property->management_moe }}</td>
<td> {{ $property->o_fees}}</td>
<td> {{ $property->contingencies}}</td>
<td> {{ $property->diligence}}</td>
<td>
<a href="{{ route('properties.show', $property->id) }}" class="btn btn-success btn-xs"><i class="fa fa-folder"></i> View </a>
<a href="{{ route('properties.edit', $property->id) }}" class="btn btn-info btn-xs"><i class="fa fa-pencil"></i> Edit </a>
<!-- Button trigger modal -->
<button type="button" class="btn btn-danger btn-xs" data-toggle="modal" data-target="#myModal">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete</span>
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Delete?</h4>
</div>
<div class="modal-body">
Do you really want to delete this project?
</div>
<div class="modal-footer">
<div class="row">
<div class="col-xs-3">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
<div class="col-xs-3 col-md-offset-4">
{!! Form::open(['route' => ['properties.destroy', $property->id], 'method' => 'DELETE']) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-success btn-md']) !!}
{!! Form::close() !!}
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /Button trigger modal -->
</td>
</tr>
@endforeach
</tbody>
<tfoot>
<tr>
<th>#</th>
<th>Address</th>
<th>City</th>
<th>Country</th>
<th>Category</th>
<th>Price</th>
<th>Loan</th>
<th>Rent</th>
<th>Mortgage</th>
<th>Manage</th>
<th>Other Fees.</th>
<th>Contingencies</th>
<th>Diligencies</th>
<th> View</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
答案 0 :(得分:0)
您必须更新系统进程以避免此类错误。
您需要在您的类别模型上添加一个雄辩的活动,该活动将释放与其相关的所有产品,使其不再属于任何类别。
使用Laravel 5.4,试试这个:
创建新活动。
<?php
namespace App\Events;
use App\Category;
use Illuminate\Queue\SerializesModels;
/**
* Class CategoryDeleted
* @package App\Events
*/
class CategoryDeleted
{
use SerializesModels;
/**
* @var Category
*/
public $category;
/**
* Create a new event instance.
*
* @param Category $category
*/
public function __construct(Category $category)
{
$this->category = $category;
}
}
为您的活动创建听众。
<?php
namespace App\Listeners;
use App\Events\CategoryDeleted;
/**
* Class DissociatePropertiesFromDeletedCategory
* @package App\Listeners
*/
class DissociatePropertiesFromDeletedCategory
{
/**
* Handle the event.
*
* @param CategoryDeleted $event
* @return void
*/
public function handle(CategoryDeleted $event)
{
$event->category->properties()->update(['category_id' => null]);
}
}
在App\Category
模型类中添加以下内容:
/**
* @var array
*/
protected $events = [
'deleted' => CategoryDeleted::class,
];
在事件服务提供商中设置事件/侦听器:
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'App\Events\CategoryDeleted' => [
'App\Listeners\DissociatePropertiesFromDeletedCategory',
],
];
您必须确保属性表中的account_id
字段可以为空。
最后,请确保您已经在类别模型上设置了关系。
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function properties()
{
return $this->hasMany('App\Properties');
}
有关详细信息,请参阅laravel eloquent event docs here。