laravel display data on a page based on id - laravel

I have a page that shows links with name of businesses that are retrieved in database like this:
Controller:
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]);
}
View:
#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:
Route::get('business/list', 'BusinessController#viewBusiness')->name('viewBusiness');
I then have added a function where user click on a link and it is taken to a page which displays all data for that specific business, however it diplays all data but for all businesses.
Controller:
function displayBusiness() {
$business = Business::all();
$address = Address::all();
return view('displayBusiness', ['business' => $business, 'address' => $address]);
}
View:
#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:
Route::get('business/{name}', 'BusinessController#displayBusiness')->name('displayBusiness');
Now here's the question, how can this code be modified so only a business that match either bussiness->name or business->id is displayed. (I guess name is taken when user clicks on a name.
Another question is how to restrict the url so that if localhost/business/{name} is not equal to any business->name in the database returns error? at the moment it shows the page no matter what you enter.
Thanks!

I do not know if I understood the question, but that may be the beginning of a solution ...
First view :
#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
Second Controller :
function displayBusiness($id) {
$business = Business::find($id);
$address = Address::find($id);
return view('displayBusiness', compact('business', 'address'));
}
Second View :
<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>
Second Route :
Route::get('business/{id}', 'BusinessController#displayBusiness')->name('displayBusiness');

Route parameters are available in the controller function as parameters. Now you can build a query with this function. If your query does not return any results, you can send the user back to the business overview.
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]);
}

Related

Undefined variable: foods

hi guys am in need of assistance , i know this seems to be an easy one but am a bit confused , i have a foreach loop in my main.blade.php file, which shows foods from my database it works fine but when its clicked it meant to lead to the individual post and thats where i get the error
Undefined variable: foods
heres my foreach loop in main.blade.php file
#foreach($foods as $food)
<li class="item">
<a href="{{ route('Foods.show', $food->id) }}">
<img src="{{ Storage::disk('local')->url('food_images/'.$food->image ) }}" class="img-responsive w-25 p-3" alt="Food" >
<div class="menu-desc text-center">
<span>
<h3> {{ $food->title }}</h3>
{{ $food->body }}
</span>
</div>
</a>
<h2 class="white"> #{{ $food->price }}</h2>
</li>
#endforeach
heres my main.blade.php controller
public function LoadHome()
{
$foods = Food::all();
$foods = Food::orderBy('created_at','desc')->inRandomOrder()
->limit(12)
->get();
return view('pages.home')->withFood($foods);
}
and heres Foods.show controller function
public function show($id)
{
$foods = Food::Find($id);
return view('foods.show')->withFood($foods);
}
please what am i doing wrong
Have you tried passing data from your controller to the view using this something like this:
public function show($id)
{
$foods = Food::Find($id);
return view('foods.show')->with('foods', $foods);
}
or, if you're passing multiple variables to the view:
public function show($id)
{
$foods = Food::Find($id);
$something = "else";
return view('foods.show', compact('foods', 'something'));
}
Your view doesn't know what $foods is at that point, so it's always good practice to check that foods is set before the loop:
#if (isset($foods) && $foods->count() > 0)
#foreach($foods as $food)
...
#endforeach
#endif
See the official Laravel docs for more information.
If you want the variable to be named foods in the view then you would need to use withFoods not withFood:
return view(...)->withFoods($foods);
As mentioned in the other answers, there are other ways to pass data to the views as well.
There is no data being passed to a view.
This is how you pass data to a view:
public function LoadHome()
{
$foods = Food::orderBy('created_at','desc')->inRandomOrder()
->limit(12)
->get();
return view('pages.home', ['foods' => $foods])
}
If you always want to have $foods in main.blade.php you should place this in a service provider
View::share('foods', Food::orderBy('created_at','desc')->inRandomOrder()
->limit(12)
->get());
https://laravel.com/docs/7.x/views#sharing-data-with-all-views

Passed data lost in Laravel paginator starting from page 2

I am trying to list people by their appRole. Here's the controller:
public function indexByAppRole(Request $request, $appRoleId)
{
$h1 = AppRole::where('id', $appRoleId)->first()->name;
return view('admin.people.index', [
'people' => $this->people->byAppRole($appRoleId),
'appRoles' => $this->appRoles->forAll(),
'h1' => 'Role: '. $h1,
]);
}
Paginator is used in the repository:
public function byAppRole($appRoleId)
{
return Person::where('person_app_role.app_role_id', $appRoleId)
->join('person_app_role', 'person_app_role.person_id', '=', 'people.id')
->select('people.*') // fix ID confusion but why?
->paginate(20);
}
The main view lists the returned people. In the sidebar, I have the following list as side-navigation:
<ul class="list-group nav nav-pills nav-stacked">
#foreach ($appRoles as $appRole)
<li>
{{ str_plural($appRole->name) }}
</li>
#endforeach
</ul>
The navigation list works on page 1 of search results or listings, but the list is not showing up on page 2 and subsequent pages. What did I do wrong?
I solved the problem. For AppRole, I also used a paginator, so this was fixed by using all() instead of paginate() to get all appRoles.
// Before...........
public function forAll()
{
return AppRole::paginate(20);
}
And:
// After............
public function forAll()
{
return AppRole::all();
}

How to pass parameters between controller methods

I am having problems getting the value of custom create method. What I want is to get the variable $student_id and place it on my findOrFail() in the index method as shown below:
ReservationController.php
public function index()
{
$student = Student::with(['sectionSubjects','sectionSubjects.section',
'sectionSubjects.subject'])->findOrFail(1); //$student_id
return $student->sectionSubjects;
}
public function create($id)
{
$student_id = $id;
$subjects = Subject::with('sections')->get();
return view('reservation.form',compact('subjects','student_id'));
}
Here's my route:
Route::resource('student', 'StudentController');
Route::resource('reservation', 'ReservationController', ['except' => ['create','show'] ]);
Route::get('reservation/{id}/create',
['as' => 'reservation.create', 'uses' => 'ReservationController#create'
]);
I have this form.blade.php that when a user click on a student it will be redirected to the custom create method in the ReservationController as seen below:
<div class="list-group ">
#inject('student', 'App\Http\Controllers\StudentController')
#foreach($student->index() as $s)
<div class="list-group-item">
<h4 class="list-group-item-heading">
{{ $s->first_name }} {{ $s->middle_name }} {{ $s->last_name }}</i>
</h4>
<h5>
ID No.: {{ $s->id_no }}</i>
</h5>
Edit Info
<a href="{{ route('reservation.create', $s->id ) }}"
class="btn btn-xs btn-danger">
Enroll
</a>
</div>
#endforeach
</div>
Now in the index method in the ReservationController, I want to fetch only values that are related to that $student_id. However, I cannot figure out to achieve this. Can anyone suggest ways to solve this?
Actually you don't have any problem expect Logic problem.
Your Controller not designed in the correct way.
You need to have something like this
//List all subjects
public function index() {
return view('reservation.form')->with('subjects', Subject::with('sections')->get());
}
//List a single subject
//If i didn't misunderstood you, you can remove this one according to the source code you're using.
public function show($id) {
return view('reservation.oneSubject')->with('subject', Subject::find($id));
}
//Enroll a student to subject
public function enroll($id, $student_id) {
//Find the section for $id
//Add student_id to that section
}
And you need to define one extra route could be GET or POST in this example i'm using GET
Route::get('/reservation/{id}/enroll/{student_id}', 'ReservationsController#enroll');
What logic should i follow?
List all subjects (will call index())
Select one subject (will call show($id))
Show students.
Click add button (will call enroll($id, $student_id)
How do i pass $id, $student_id to enroll?
Your reservations resource will have these routes.
/reservations
/reservations/{id}/store
etc..
id parameter in your example, Pointing to Subject not Student.
Let's say you've a show($id) function which will show single subject and list of students,
return view(...)->with('subject', Subject::find($id)->with('students', YOUR_STUDENTS);
In the view, iterate through students, assuming you've $students
#foreach($students as $student)
Enroll student
#endforeach
I don't have show() function!
Since you don't have a show function that will display single subject, Same logic will apply here,
Iterate through subjects
Display subject
Iterate throught students
Generate anchor tags as the example above
So you'll have something like this,
#foreach($subjects as $subject)
<h1>{{ $subject->title }}</h1>
#foreach($students as $student)
<div class="students">
<h2> {{ $student->name }}</h2>
Enroll
</div>
#endforeach
#endforeach

search form using laravel shows 'Call to a member function getNumCommentsStr() on a non-object'

i have made a search bar using laravel, but it did not succeed. it shows the error as said below. And it seems that something wrong with my post object. But i do not know where.
source code as follows, thanks for helping.
//the searchController for seach code
public function search(){
$keyword = Input::get('keyword');
if(empty($keyword)){
return Redirect::route('/');
//->with('message',array('type' => 'alert', 'content' => '不能为空'))
}
$posts = Post::where('content', 'like', '%'.$keyword.'%')->orderBy('created_at', 'desc')->paginate(10);
$tags = Tag::where('count','>','0')->orderBy('count','desc')->orderBy('updated_at', 'desc')->take(20)->get();
return Redirect::route('searchResults')->with('posts', $posts->toArray())->with('tags',$tags);
}
public function searchResults(){
return View::make('frontend.search.search',['posts' => Session::get('posts'),'tags' => Session::get('tags')]);
}
//search bar route
Route::get('/searchResults', array(
'uses' => 'SearchController#searchResults',
'as' => 'searchResults'
));
Route::post('/search', array(
'before' => 'csrf',
'uses' => 'SearchController#search',
'as' => 'search'
));
//search from
{{ Form::open(array('url'=>'/search','method' => 'post','class'=>''))}}
{{ Form::token()}}
<label for="docSearch">
<i class="fa fa-search"></i>
</label>
<div class="searchInput">
{{Form::text('keyword', '', array('class'=>'docsSearch', 'placeholder'=>'搜索论坛动态...'))}}
{{ Form::submit('提交',array('class'=>''))}}
{{Form::close()}}
//now i just wanna to get it like this:
#if(!$posts)
{{'<section class="oneQuestion">sorry,no content...</section>'}}
#else
#foreach($posts as $post)
<section class="oneQuestion">
<div class="askResult">
<!-- <i class="fa fa-question notSolved"></i>
<i class="fa fa-check solved" style="display:none;"></i> -->
#if($post->getNumCommentsStr() == 0)
<a href="{{URL::route('viewPost', array('id' => $post->id))}}#reviews" class="notSolved"><span class="post_comment_Num">{{$post->getNumCommentsStr()}}</span>
<span> 回答</span>
</a>
#else
<a href="{{URL::route('viewPost', array('id' => $post->id))}}#reviews" class="solved"><span class="post_comment_Num">{{$post->getNumCommentsStr()}}</span>
<span> 回答</span>
</a>
#endif
</div><!--
--><div class="titlePart">
<span>
{{$post->user->username}}
{{$post->created_at->diffForHumans()}}
</span>
<a href="{{ URL::route('viewPost', $post->id)}}">
{{-- {{ substr($post->content,0,200) }}... --}}
{{$post->title}}
</a>
<div class="tagWrapper">
#foreach ($post->tags as $tag)
<span class="askTag" title="">{{$tag->name}} </span>
#endforeach
</div>
</div>
</section>
#endforeach
#endif
<div class="forumLink">
{{$posts->links()}}
</div>
//it showed me an error:
**Call to a member function getNumCommentsStr() on a non-object**
and my getNumCommentsStr like:
public function getNumCommentsStr()
{
$num = $this->reviews()->count();
// if($num == 1){
// return "1";
// }
return $num;
}
code seems a lot but i wanna to make it clear so you can find any errors. Thanks again.
Edit 2
Thanks for NightMICU's suggest and I change
Redirect::route('searchResults')->with('posts', $posts->toArray())->with('tags',$tags);
to the following:
Redirect::route('searchResults')->with('posts')->with('tags',$tags);
THE result is without any alert any more, it just shows: sorry, no content...
And did not show any search result, any problem? Thanks
EDIT TWO
//delete the searchResult method, all in one search method so that i can return the view in right in the search method.
public function search(){
$keyword = Input::get('keyword');
if(empty($keyword)){
return Redirect::route('developer');
//->with('message',array('type' => 'alert', 'content' => '不能为空'))
}
$posts = Post::where('content', 'like', '%'.$keyword.'%')->orderBy('created_at', 'desc')->paginate(10);
$tags = Tag::where('count','>','0')->orderBy('count','desc')->orderBy('updated_at', 'desc')->take(20)->get();
return View::make('frontend.search.search',['posts' => $posts,'tags' => $tags]);
}
EDIT 3
there are two questions exsiting here.
ONE is that when i change to that ,it can output the result but all the result the database has. Not the keyword results.
Two is that when there are extra page, once i open the link http://localhost/html5lav/public/search?page=2, it just show an error:
No query results for model [Post].
The initial issue most likely has to do with the unusual way you are displaying the search results; by passing the Eloquent collections via session to another method, only to display the View. You were also converting the Post Eloquent collection to a regular array with ->toArray(), pagination requires a collection rather than an array.
The solution for that part:
public function search(){
$keyword = Input::get('keyword');
if(empty($keyword)){
return Redirect::route('/');
//->with('message',array('type' => 'alert', 'content' => '不能为空'))
}
$posts = Post::where('content', 'like', '%'.$keyword.'%')->orderBy('created_at', 'desc')->paginate(10);
$tags = Tag::where('count','>','0')->orderBy('count','desc')->orderBy('updated_at', 'desc')->take(20)->get();
return View::make('frontend.search.search')->with('posts', $posts)->with('tags', $tags);
}
After taking care of the initial issue, you reported that the pagination links are not working as expected - you click on Page 2 and do not have any Post results. If the route for the page where the user inputs a search term is also /search, there is a conflict. Instead, change the route that the search form posts to, perhaps /searchResults (which then loads the results using the search method). You may also want to consider using a GET rather than POST request, allowing users to bookmark their search results or share a link.
Regarding the issue of displaying all of the entries from the posts table, you need to review MySQL raw queries in Laravel. Swing by the documentation and look them up.

generate link to pages in laravel issue

I have a problem with link in laravel.
I have this route:
$lingua = Request::segment(1);
Route::group(array('prefix' => $lingua), function()
{
Route::get('/', 'ItemController#menu');
Route::get('/{idcampo}/{idcat}','ItemController#show');
});
The first is language and request the 1st segment, and use as prefix. in /
THis is my ItemController Controller
public function menu()
{$lingua = Request::segment(1);
return View::make('index', ['categorie'=>DB::table('cat_nome')->join('lingua', 'cat_nome.id_lingua', '=', 'lingua.id') ->where('lingua.lingua','=',$lingua)->get(),
'campi' => DB::table('campo_nome')->join('lingua', 'campo_nome.id_lingua', '=', 'lingua.id') ->where('lingua.lingua','=',$lingua)->get(),
'lingua'=>$lingua,
]
);
}
public function show($camps,$cats)
{$lingua = Request::segment(1);
return View::make('categorie', ['categorie'=>DB::table('cat_nome')->join('lingua', 'cat_nome.id_lingua', '=', 'lingua.id') ->where('lingua.lingua','=',$lingua)->get(),
'campi' => DB::table('campo_nome')->join('lingua', 'campo_nome.id_lingua', '=', 'lingua.id') ->where('lingua.lingua','=',$lingua)->get(),
'dd' => DB::table('description')->join('lingua', 'description.id_lingua', '=', 'lingua.id')->where('lingua.lingua','=',$lingua)->where ('description.id_cat','=',$cats)->where ('description.id_campo','=',$camps)->select('description.descrizione')->get(),
'lingua' => $lingua,
]);
}
In index i query a the entries of a menu.
#foreach ($campi as $campo)
{{$campo->nome}}
<ul class="list-unstyled">
#foreach($categorie as $categoria)
<li> {{$categoria->nome}} </li>
#endforeach
</ul>
#endforeach
Now when i pass to the controller, i keep the menu visualized and i visualize the single entries of the database (the description).
My problem is that when i click the first time on the link, which appear to be:
language/id1/id2
I go in the right page, visualize the description of the product BUT now the link on the side menu became:
language/id1/language/id1/id2
But it should always be language/id1/id2 even when i am in Itemcontroller#show
The second time the link are generated in the side menu, something is added on the link, and i can't quite understand why.
You might try to use URL::to like this:
<a href="{{ URL::to($lingua. '/'. $campo->id_campo. '/'. $categoria->id_cat) }}">

Resources