Laravel中如何获取对象动态ID并展示其关联数据
调整步骤
1. 改造Blade模板与Ajax逻辑
首先给所有精选项目的可点击元素绑定项目ID,示例如下:
<!-- 精选项目模块的单个项目卡片示例 --> @foreach($recommendProjects as $project) <div class="project-item" data-project-id="{{ $project->id }}"> <!-- 项目名称、封面等展示内容 --> <h3>{{ $project->name }}</h3> </div> @endforeach
然后调整Ajax代码,修改为点击项目时动态传入ID发起请求:
<script> // 全局配置CSRF令牌,避免Laravel POST请求419权限错误 $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $(document).ready(function(){ // 绑定精选项目点击事件 $('.project-item').click(function(){ // 获取当前点击的项目ID const projectId = $(this).data('project-id'); // 可根据实际业务逻辑获取筛选参数,比如property_type const property_type = $('input[name="property_type"]:checked').val() || ''; getProperties(projectId, property_type); }); function getProperties(projectId, property_type) { // 发起请求前清空原有房产列表,避免内容累加 $('#property-data').empty(); $.ajax({ url: `/handpickedproperties/${projectId}`, type:'POST', data:{'property_type': property_type}, success:function(response){ if(response.success){ var str = ''; stringlength = 135; if($( window ).width()<1363) var stringlength = 100; $.each(response.data, function(k,v){ // 原有列表拼接逻辑保持不变 description = v.description; if (description.length > stringlength) description = description.substr(0,stringlength)+'.....more'; photos = JSON.parse(v.images); if(jQuery.isEmptyObject(photos)){ image_count = 0; cover_photo = '/images/default/photo not available.png'; } else{ image_count = Object.keys(photos['withPhotos']).length; cover_photo = photos.coverPhoto; } area_conversion = JSON.parse(v.area_conversions); str += '<div class="property-box" data-aos="fade-up">\ <div class="pic-area">\ <figure><img src="'+cover_photo+'">\ <span class="photo-count">\ <img src="images/photos-icon.png">'+image_count+'</span>\ </figure>\ </div>\ <div class="listing-property-details">\ <a href="/viewPropertyDetails/'+v.id+'">\ <h5>'+v.name+' in '+v.address+'</a><a href="javascript: void(0)" onclick="addFavourite(`'+v.id+'`)" class="wishlist" style="margin-top:0"><img src="/images/home/heart2.png" id="pic_'+v.id+'"></a><a href="/viewPropertyDetails/'+v.id+'"></h5>\ <span class="price-box">\ <strong>'+v.currency+v.price+v.price_unit+'</strong>\ '+v.currency+' '+v.price_per_area+'/sq.ftadsds.\ </span>\ <span class="area-box">\ <img src="/images/listing-area.png">\ <strong><span class="sq_ft" style="width:75%;display:inline-block;">'+v.area_per_sq_ft+' sq.ft.</span>\ <span class="sq_mt" style="width:75%;display:none;">'+area_conversion.sq_mt+' sq.mt.</span>\ <span class="sq_yrd" style="width:75%;display:none;">'+area_conversion.sq_yrd+' sq.yrd.</span></strong>\ ('+v.carpet_area+') Carpet Area\ </span>\ <span class="bed-box">\ <img src="/images/listing-bed.png">\ <strong>'+v.bedroom+' BHK</strong>\ </span>\ <span class="bath-box">\ <img src="/images/listing-bath.png">\ <strong>'+v.bathroom+' Bath</strong>\ </span>\ <div class="clear"></div>\ <p class="property-brief" style="color:black;">'+description+'</p></a>'; if(v.featured == 1) str += '<label style="margin-right: 5px;" class="featured-highlight-buttton">Featured</label>'; if(v.verified == 1) str += '<label style="margin-right: 5px;" class="highlight-buttton">Verified</label>'; if(v.construction_status == 3) str += '<label style="margin-right: 5px;" class="highlight-buttton">Under Construction</label>'; if(v.construction_status == 4) str += '<label style="margin-right: 5px;" class="highlight-buttton">Ready to Move</label>'; str += '</div>\ <div class="listing-box-bottom">\ <span>\ Posted on '+v.creation_date+' by '+v.created_by+'\ <a href="/total-listed-properties" target="_blank"><strong>'+v.posted_by+'</strong></a>\ </span>\ <a href="#" onClick = "contactDetails(`'+v.id+'`);">Contact '+v.posted_by+'</a>\ </div>\ </div>'; }); $('#results_number').empty(); $('#results_number').append(Object.keys(response.data).length); $('#property-data').append(str); $('#no-result-found-div').hide(); } else{ $('#property-data').empty(); $('#results_number').empty(); $('#results_number').append(0); $('#no-result-found-div').show(); } } }); } }); </script>
注意:需要在页面head标签中添加<meta name="csrf-token" content="{{ csrf_token() }}">,否则POST请求会触发419权限错误。
2. 修正控制器返回逻辑
原控制器中查询到房产数据后错误返回了视图,ajax请求需要返回JSON格式数据,修改如下:
public function handpickedProperties(Request $request,$id) { try { $data = $request->all(); $validator = Validator::make($data, [ // 可按需添加参数校验规则,比如property_type的校验 ]); if ($validator->fails()) return $this->sendError("Validation Failure",$validator->errors(),403); $price_min = 0; $price_max = 10000000; $search = PropertyServices::fetchHandpickedProperties($request->search,$request->type,$request->city,$request->property_type,$price_max,$price_min,$id); if(is_array($search)) // 把返回视图改为返回成功JSON return $this->sendSuccess('查询成功', $search); else if($search == 0) return $this->sendError('Property not found',[],206); else if($search == null) return $this->sendError('Property not found. Due to Exception in Service',[],500); } catch(Exception $e) { Log::error('Exception encountered. PropertyController->searchProperties Exception: '.$e); return $this->sendError('Property not found. Due to Exception.',[],500); } }
3. 修正Service层查询条件
把固定写死的project_id=2改为传入的动态ID即可:
public function fetchHandpickedProperties($search,$type,$city,$property_type,$price_max,$price_min,$id) { try { // 替换固定ID为传入的$id参数 $result = Property::where('project_id', $id) ->select('description','images','id','address','name','currency','price','price_unit','price_per_area','area_per_sq_ft','area_conversions','bedroom','bathroom','created_by','posted_by',\DB::raw('DATE_FORMAT(created_at,"%M-%d-%Y") as creation_date'),'carpet_area','verified','construction_status','featured','lat','long') ->get() ->toArray(); return $result; } catch(Exception $e) { Log::error('Exception encountered. PropertyServices->searchProperty Exception: '.$e); return null; } }
4. 路由确认
确保routes/web.php中存在对应路由配置:
Route::post('/handpickedproperties/{id}', [PropertyController::class, 'handpickedProperties']);
修改完成后点击不同的精选项目,即可动态加载对应项目绑定的房产数据。
内容的提问来源于stack exchange,提问作者Manasvi Nagpal
相关产品推荐
相关产品推荐

