On my index.blade i like to show two different sets of data, one is a list of computers the other one list of categories. two different type of data. in my controller I have
public function index()
{
// Select data from table assets
$assets = DB::table('assets')->where('status', '1')->orderBy('type', 'asc')->paginate(10); //pass all the employees to a Var and send it to our page using "with" also puts page # at the bottom
//select data from table assetrefs
$categories = DB::table('assetrefs')->get();
//bind data and send using 'with'
return view('assets.index')->with('assets', $assets)->with('categories', $categories);
}
on my view side I have these two loops
#if(count($categories) > 1)
#foreach($categories as $row)
{!!Form::open(['action' => ['AssetsController#showType', $row->title], 'method'=> 'POST', 'class'=> 'pull-left'])!!}
{{Form::submit('Show '. $row->title, ['class' => 'btn btn-danger'])}}
{!!Form::close()!!}
#endforeach
#else
<p> no content </p>
#endif
This shows a bunch of button with categories
<div class="well"></div>
<!-- lists all the available assets in a div all types are mixed but sorted -->
#if(count($assets) > 1)
#foreach($assets as $asset)
<div class="well">
<h3>{{$asset->type}}, {{$asset->make}} - {{$asset->model}} </h3>
<small> {{$asset->sn}}</small>
<small> View this account</small>
</div>
#endforeach
{{$assets->links()}}
#else
<p> no content </p>
#endif
this shows a list of all computers
When I load the page I get
2/2 ErrorException
Undefined variable: categories (View: resources\views\assets\index.blade.php)
Can you please pass data to view by making use of array instead of with like below:
public function index()
{
// passing data without with
$data['assets'] = DB::table('assets')->where('status', '1')->orderBy('type', 'asc')->paginate(10);
$data['categories'] = DB::table('assetrefs')->get();
return view('assets.index',$data);
// in case if you want to use with then
// return view('assets.index')->with($data);
}
Or even if you don't want to use $data variable want to keep $asset and $categories variable as it is then
public function index()
{
// passing data without with
$assets = DB::table('assets')->where('status', '1')->orderBy('type', 'asc')->paginate(10);
$categories = DB::table('assetrefs')->get();
return view('assets.index',compact('assets','categories'));
}
You can check how compact function is working in php by url -> http://php.net/manual/en/function.compact.php
Try this in your Controller in place of your view() call:
return view('assets.index', compact('assets', 'categories'));
Have a look at Passing Data To Views and you'll see view()->with() is suited for passing individual pieces of data whereas passing an array as a second argument is required for multiple variables. Here we're passing an array of your already defined assets and categories via PHP's compact function.
Related
I'm building a forum, and I'm trying to implement a categories page. The page is working as of now, it's dynamic so it lists all categories stored in the database. However I want to be able to click on a category and be taken to a template page. From this template page I want to pass a category ID (defined in the database as a primary key). Then all posts with the matching category ID will be displayed. I'm having trouble passing this category ID to my category page template.
Any help would be extremely appreciated!
(How categories are displayed in a list:)
#foreach($categories as $row)
<div id="newscontainer" class="container">
<?php $categoryid = $row->id; ?>
<span id='categoryname'><?= $row->categoryname ?><br></span>
<span id="categorydescription"><?= $row->categorydescription?></span>
</div>
<br>
#endforeach
Thanks!
First of all define a route in web.php:
web.php:
Route::get('category/{category}','YouController#YourCatFunction')->name('categories.list');
in your controller:
public function YourCatFunction(Category $category)
{
// here you can return view for post with that category and then display them
return $category;
}
then in your view:
#foreach($categories as $row)
<div id="newscontainer" class="container">
<span id='categoryname'>{{ $row->categoryname }}<br></span>
<span id="categorydescription">{{ $row->categorydescription }}</span>
</div>
<br>
#endforeach
You can create a web route which will handle the category calls and return the view with that category and it's posts.
First you create a route like this:
Route::get('category/{category}', 'CategoriesController#show')->name('category.show');
Then you can access this Category inside the controller and load the posts and return them like this:
public function show(Request $request, Category $category) {
return view('category.show', compact('category'));
}
Then in your view you would have something like this where you loop over available posts:
#foreach($category->posts as $post)
// do something
#endforeach
To call the route you can simply create this link:
Show
As I can see, your base namespace is ULMG, so the correct way to your Category class would be ULMG\Category
You can try this one as well.
Route web.php
Route::get('category/{categoryid}', ['as'=>'category.show','uses'=>'CategoriesController#show');
Controller CategoriesController.php
public function show($categoryid){
// some of your code.
$categoryid = DB::table('category')->select('categoryId');
return view('category.show', compact('categoryId'));
// don't forget if you have some variables and you want to view it at blade just put it inside the compact
}
View blade category.show.blade.php
#foreach($categories as $row)
<div id="newscontainer" class="container">
<span id='categoryname'>{{ $row->categoryname }}<br></span>
<span id="categorydescription">{{ $row->categorydescription }}</span>
</div>
#endforeach
For anyone else who is having the same issue:
(I had a eureka moment...)
My forums.blade.php file (where the user selects the category they want to view:
Here, it's calling the category route (which is where the posts will be displayed) then it's setting the category ID in one url. It will look like this in the browser: www.example.test/category/(ID) (so when I query the database for posts under that category it will extract them).
<span id='categoryname'><?= $row->categoryname ?><br></span>
My web.php file:
I basically grabbed the id from the URL which was passed through when the user clicked on the link.
Route::get('/category/{id}', 'CategoriesController#getid');
My CategoriesController.php file:
Here I have defined a function, so in the web.php it knows to go to the function with the attribute of getid. Once it has found the correct function it sets the $catid the same value as $id. Then it returns to the categorytemplate view (which is the template requiring the ID in the first place to display the posts) with the $catid variable in a compact function.
public function getid($id){
$catid = $id;
return view('categorytemplate', compact('catid'));
}
I hope my explanation is clear enough to understand. And I hope this can help someone else with this issue in the future!
Thanks again to everyone else suggesting ideas.
I'm using sort function and pagination but the problem when I use sort for any column works fine but when I click to the next page using pagination the sort change and have to click on the column again for sorting.
so how to keep sorting while using pagination?
<tr>
<th>
<div class="checkbox checkbox-replace">
<input type="checkbox" id="chk-3">
</div>
</th>
<th>#sortablelink('details','Details')</th>
<th>#sortablelink('postingdate','Date')</th>
<th>#sortablelink('description','Description')</th>
<th>#sortablelink('amount','Amount')</th>
<th>#sortablelink('type','Type')</th>
<th>#sortablelink('slip','Slip#')</th>
<th>#sortablelink('vendor_id','Vendor')</th>
<th>#sortablelink('category_id','Category')</th>
</tr>
public function index()
{
$checks = Checks::orderBy('id', 'asc')->get();
$checks= Checks::sortable()->paginate(5);
return view('home',compact('checks'));
}
You can append query string to your link by doing this :
{{ $users->appends(['sort' => 'votes'])->links() }}
replace sort by your sortable query, and votes by something like request()->sort
According to this page, you also can do your pagination like this:
//Controller
public function index()
{
$checks = Checks::orderBy('id')->paginate(5);
$links = $checks ->appends(['sort' => 'id'])->links();
return view('home', compact('checks', 'links'));
}
And in your view, you can just call your pagination links like this
{{ $links }}
Hope it helps. Cheers!
{{links()}} will still give a messed up sort when you paginate. This is the same as {!! link() !!} also and {{ $checks->links()}}
Rather, use the code below. It will correct the error.
//for the Controller
public function index()
{
$checks = Checks::sortable()->paginate(5);
return view('home', compact('checks'));
}
//for the blade template in laravel append this in div after the table
{!! $checks->appends(\Request::except('page'))->render() !!}][1]
you can use this line in your blade file
{!! $product->appends(\Request::except('page'))->render() !!}
I have set up two model with its row in table. And made a single form to fill both tables and it works perfectly
Tour.php
public function featuredImage()
{
return $this->hasOne('App\FeaturedImage');
}
tours table
id|name|content|featured_status
featuredImage.php
public function tour()
{
return $this->belongsTo('App\Tour');
}
Featured_images table
id|tour_id|path|name
Code in my controller to pass data to view.
$tours = Tour::where('featured', 1)->get();
return view('public.pages.index')
->withTours($tours);
Code in my view
#foreach($tours as $featured)
<div class="thumbnail">
<img src="{{$featured->featuredimage->path}}" alt="{{$featured->featuredImage->name}}">
</div>
<h4>{{$featured-name}}</h4>
#endforeach
The trouble is I'm not able to fetch featured images by writing
{{$featured->featuredimage->path}}
and the error is
Trying to get property of non-object
on the line {{$featured->featuredimage->path}}. I have used this method in my previous project and it had worked perfectly but it isn't going well in this one.
I tried replacing {{$featured->featuredimage->path}} with {{$featured->featuredImage->path}} but didn't worrked out.
Do this:
{{ $featured->featuredImage()->path }}
Also, you're creating a lot of additional queries here. You should use eager loading to solve N + 1 problem:
$tours = Tour::with('featuredImage')->where('featured', 1)->get();
And display data with:
{{ $featured->featuredImage->path }}
I have a Laravel PHP Photo Gallery application that allows the user to create an album and then insert photos into an album of their choice from a drop down list. This requires the user to create the album first since the drop down list is dynamic based on which albums actually exist. The drop down list is currently functioning properly but it does not display albums (array elements) alphabetically.
I've tried using the 'sort()' method but the problem is that the array element ids then become switched/re-sorted when doing so. I do not want the array ids to be re-sorted since this will put photos into the wrong albums.
So I want to know if there is a way to display the albums alphabetically in a drop down list while not re-sorting their array element ids.
Controller:
public function create()
{
$stoneArray = $this->stone->all()->toArray();
if (empty($stoneArray)) {
$dropdown[0] = 'There are no stones';
}
foreach ($stoneArray as $stone) {
$dropdown[$stone['stone_id']] = $stone['stone_name'];
// sort($dropdown); /* This re-sorted the array element ids */
}
$data = array('type' => 'stone_photo', 'dropdown' => $dropdown);
$this->layout->content = \View::make('forms.stones.new-photo', $data);
}
View:
<div class="form-group">
{{ Form::label('stone_id', 'Stone: ') }}
{{ Form::select('stone_id', $dropdown, array('class' => 'form-control')) }}
</div>
Any help is greatly appreciated! Thank you!
EDIT
I'm making some assumptions here about your file structure, but it should give you the idea.
In: app\Acme\repositories\Eloquent\EloquentStoneRepository.php or whatever you called it, there's a function:
public function all()
{
return Stone::all();
}
(I think that's what it looks like, but I'm not positive). Try changing that to:
public function all()
{
return Stone::orderBy('column_name', 'asc')->get();
}
If you use all() somewhere else and don't want it sorted, consider adding another function:
public function all_sorted()
{
return Stone::orderBy('column_name', 'asc')->get();
}
Hope that helps!
Edit:
Changed ->all() to ->get() so eloquent can properly sort it.
At the moment I'm getting all the rows from my table, and display every category on the page. Now I want to make something new but I'm a bit stuck after trying a few things.
So now I have a link called 'photos' and when that's being clicked all the photos are being shown. Now I want to have a submenu so that I can only see the photos of a certain category. This is how a table can look like
pk imgUrl category
--------------------
1 ... portret
2 ... nature
3 ... portret
4 ... cars
When navigating to www.mysite.com/photos, then this displays all my photos regardless of the category.
Now I want to add the functionality when going to www.mysite.com/photos/portret that I only see photos from the category portret.
I was able to create the links dynamically and they go to the correct URL (www.mysite.com/photos), but the page is empty. So I don't know what is going wrong. Routing?
I'll post what I have tried and what I currently have below.
Before the navigation was static, but now that I want it dynamic I added the NavController
public function index()
{
//
//return Photo::all();
$title = "Photo";
$photos = Photo::orderBy('category')->get();
return View::make('photo')->with('title', $title)->with('photos', $photos);
//QUERY - Eloquent
//return Photo::all();
}
And it's corresponding view is nav.blade that contains this (This prints out my dynamic links)
<?php
$category = "";
?>
<ul>
#foreach($photos as $photo)
#if($category != $photo->Category)
<li> {{ $photo->Category }} </li>
<?php $category = $photo->Category; ?>
#endif
#endforeach
</ul>
Then in my route I have so I can navigate to the dynamic pages
Route::get('photos/{theme}', array('as' => '{theme}', 'uses' => 'PhotosController#show'));
Then here in my PhotosController I have
public function show($theme){
$photos = Photo::where('category', $theme);
return View::make('photo')->with('title', $theme)->with('photos', $photos);
}
And in my view photos.blade
<?php
$category = "";
?>
#foreach($photos as $photo)
{{ HTML::image("img/$photo->Link", "$photo->Title", array("class"=>"thumbnail thumbEffect")) }}
#endforeach
So I don't see or understand what I'm doing wrong. Also when going to the page www.mysite.com/photos/portret, the dynamic links don't appear anymore while this should be as it's only in the nav.blade that's being included in my template.
Can someone help me please?
EDIT: Most of my work here is due an other Q/A I found on SO and that's this Laravel Creating Dynamic Routes to controllers from Mysql database
Your code looks almost good to me, but you forgetting to get your photos from the database:
public function show($theme)
{
$photos = Photo::where('category', $theme)->get(); /// here
return View::make('photo')->with('title', $theme)->with('photos', $photos);
}