我有一个页面,其中显示了在数据库中检索到的企业名称的链接,如下所示:
控制器:
public function viewBusiness() {
// Return our "website" object
$business = Business::all();
// Pass the contents of the "html" property to the view
return view('viewBusiness', ['business' => $business]);
}
查看:
@extends('master') @section('title', 'Live Oldham') @section('content')
@section('content')
@foreach ($business as $businesses)
<a target="_blank" href="{{ url('business/' . $businesses->name) }}"> {{($businesses->name) }}
</a> @endforeach
@endsection
路线:
Route::get('business/list', 'BusinessController@viewBusiness')->name('viewBusiness');
然后,我添加了一个功能,用户点击链接,然后将其转到显示该特定商家的所有数据的页面,但是它会覆盖所有数据,但适用于所有商家。
控制器:
function displayBusiness() {
$business = Business::all();
$address = Address::all();
return view('displayBusiness', ['business' => $business, 'address' => $address]);
}
查看:
@foreach ($business as $businesses)
<p>{{$businesses->name}}</p>
<p>{{$businesses->email}}</p>
@endforeach
@foreach ($address as $addresses)
<p>{{$addresses->firstline_address}}</p>
<p>{{$addresses->secondline_address}}</p>
<p>{{$addresses->town}}</p>
<p>{{$addresses->city}}</p>
<p>{{$addresses->postcode}}</p>
<p>{{$addresses->telephone}}</p>
@endforeach
路线:
Route::get('business/{name}', 'BusinessController@displayBusiness')->name('displayBusiness');
现在问题是,如何修改此代码,以便只显示与商务 - &gt; name或business-&gt; id匹配的商家。 (我想当用户点击名字时会采用名称。
另一个问题是如何限制网址,以便如果localhost / business / {name}不等于数据库中的任何business-&gt;名称返回错误?无论你输入什么内容,它都会显示页面。
谢谢!
答案 0 :(得分:2)
我不知道我是否理解了这个问题,但这可能是解决方案的开始......
第一个观点:
@extends('master') @section('title', 'Live Oldham')
@section('content')
@foreach ($business as $businesses)
<a target="_blank" href="{{ url('business/' . $businesses->id) }}"> {{($businesses->name) }}
</a> @endforeach
@endsection
第二名管制员:
function displayBusiness($id) {
$business = Business::find($id);
$address = Address::find($id);
return view('displayBusiness', compact('business', 'address'));
}
第二视图:
<p>{{$business->name}}</p>
<p>{{$business->email}}</p>
<p>{{$address->firstline_address}}</p>
<p>{{$address->secondline_address}}</p>
<p>{{$address->town}}</p>
<p>{{$address->city}}</p>
<p>{{$address->postcode}}</p>
<p>{{$address->telephone}}</p>
第二条路线:
Route::get('business/{id}', 'BusinessController@displayBusiness')->name('displayBusiness');
答案 1 :(得分:0)
路径参数在控制器功能中可用作参数。现在,您可以使用此函数构建查询。如果您的查询未返回任何结果,您可以将用户发送回业务概述。
function displayBusiness($name) {
$business = Business::where('name', $name)->orWhere('id', $name)->first();
if ($business === null)
{
// No business with this name or id found.
// Redirect to businesses list page.
}
$address = Address::all();
return view('displayBusiness', ['business' => $business, 'address' => $address]);
}