Laravel ForEach Into Separate DIVs - php

Im working on a project that will display articles based on a user's interest. I have a user_table, follower_table, and article_table. Currently i am able to get the user_id and grab all their associated interests from the follower_table and each article produced under their interest. Im using Foreach to loop through all their articles. However, now i want to be able to put each article into a different div based on their type. In order to be able to have varying sizes and color. What is the best way to filter the foreach loop? Here is my code below.
follower_table is set up:
user_id:(this is the person/interest you follow)
follower_id: (this is your id);
article_table is set up:
id
user_id
type: (music,fashion,events, dance)
title
body
photo
The UserController:
class UserController extends Controller
{
public function index ()
{
$ilike = Auth::id();
$ifollow = DB::table('followers')->where('follower_id', $ilike)->lists('user_id');
$articles = DB::table('articles')
->whereIn('user_id', $ifollow)->get();
//$articles = DB::table('followers')->lists('title', 'name');
//$articles = DB::table('followers')->where('follower_id', $ilike)->pluck('user_id');
//$articles = Article::all();
return view('pages.user', compact('articles'));
}
}
user.blade.php:
<div class = "grid">
#foreach($articles as $article)
<div class="grid-item ">
<img src="/image/article/detail/{{$article->id}}.jpg"/>
</div>
#endforeach

Since you are passing an Article request, you can use the $article->type attribute you declared, to use it to call css div classes.
#foreach($articles as $article)
<div class="grid-item {{$article->type}}">
<img src="/image/article/detail/{{$article->id}}.jpg"/>
</div>
And then create the desired colors in your app.css (or less/scss files):
.music {
}
.fashion{} .events{} .dance{};

Related

PHP Laravel how to sort by using two tables

I have two MySQL tables in my Laravel-application, one called categories and the other called employees. The structure of the categories-table is:
id
category
order
and the employees table also has columns called:
id
category
order
So, lets say I have categories like: Consultants, Programmers and Administration and when I create an Employee in the backend I can assign the new employee to one of these categories. Now in the frontend of my Laravel-application I want the Employees displayed by the categories, and also the categories by order they are given. Let's say Consultants has order of 2, Programmers order of 1 and Administration order of 3.
Right now my controller looks like this:
use App\Employee;
class EmployeesController extends Controller
{
public function index()
{
$employees = Employee::all()->groupBy('category');
return view('app.employee.index', compact('employees'));
}
}
and my blade view file:
#foreach ($employees as $category => $workers)
<div class="col text-center mb-6">
<h2>{{ $category }}</h2>
</div>
<div class="row px-4 px-xl-10">
#foreach($workers->sortBy('order') as $worker)
// content of the employee
#endforeach
</div>
#endforeach
This sorts the employees correctly by simply using the categories of the Employees-table but with this I'm not able to sort by categories like I want to as described above.
So, can someone help me out?
EDIT
As an example I want the output look like this:
Programmers (since this category has order of 1)
// employees with category "programmers" here
Consultants (2)
// employees with category "consultants" here
Administration (3)
// employees with category "administration" here
To me you column definitions are a bit confusing, may I suggest a change to your columns:
Table 'categories'
------------------
id
name
order
Table 'employees'
-----------------
id
category_id
Add a foreign key to the employees table:
$table->foreign('category_id')->references('id')->on('categories')
And then your models could be mapped to each other with relationship methods:
class Employee extends Model
{
public function category()
{
return $this->belongsTo(Category::class);
}
}
class Category extends Model
{
public function employees()
{
return $this->hasMany(Employee::class);
}
}
So with this in place we can simply query the database from the controller by:
use App\Category;
class EmployeesController extends Controller
{
public function index()
{
$categories = Category::orderBy('order')->get();
return view('app.employee.index', compact('categories'));
}
}
and display the results in your blade view:
#foreach ($categories as $category)
<div class="col text-center mb-6">
<h2>{{ $category->name }}</h2>
</div>
<div class="row px-4 px-xl-10">
#foreach($category->employees as $employee)
// content of the employee
#endforeach
</div>
#endforeach
I think you must change your query to :
$categories = Category::with(['employees'=>function($q){
$q->orderBy('order');
}])->orderBy('order')->get();

How Would I Send Data To a Controller

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.

Laravel - Selecting data from two different tables to show on blade.html

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.

Issue in fetching data from db to the views in laravel 5.2

Im new to laravel and studying it by creating some test projects myself in laravel 5.2. But i got stuck now with some issue in fetching data correctly from db in laravel 5.2 and display the result. I have a menu table in my db with fields -> id, menutype, itemname, itemprice, itemimage with some datas in it. I want to display it on my webpage in a specific way like as seen on the below given screenshot.
See:
And this one is my db table screenshot with the values on it. See:
i added the below codes in my Controller (GuestController.php)
public function menu() {
$result=DB::table('menu')->select('menutype')->distinct()->get();
return view('guest.menu')->with('data',$result);
}
and in the View (menu.blade.php), i had given the below code:
<div class="row">
#foreach($data as $row)
<div class="col-1-3">
<div class="wrap-col">
<h3>{{$row->menutype}}</h3>
<?php
$item=DB::table('menu')->where('menutype', $row->menutype)->get();
?>
#foreach($item as $row)
<div class="post">
<img src="assets/images/{{$row->itemimage}}"/>
<div class="wrapper">
<h5>{{$row->itemname}}</h5>
<span>Rs.{{$row->itemprice}}/-</span>
</div>
</div>
#endforeach
</div>
</div>
#endforeach
</div>
This works perfectly and i am getting the desired output as seen on the products page screenshot given above. But i know this method is not correct, because i am giving the query statement on the View itself like as given below to fetch data and its against the MVC concept:
<?php $item=DB::table('menu')->where('menutype', $row->menutype)->get(); ?>
So is there any other simple and better way i can implement to get the above said desired output along with keeping the MVC Standards?? Please help! Thanks in advance...
Laravel's Collection can really help you out with this. Specifically, the groupBy method. First, you get all of the menu items with all the data. Then, you use the groupBy method on the Collection to group the menu items into separate arrays based on their menutype. You can then use this one Collection to do all the work in your view.
The code is shown below. You can combine a couple of the lines into one if you'd like, but it is broken out into multiple lines to show all the steps:
public function menu() {
// get all the menu items
$menuArray = DB::table('menu')->get();
// create a Laravel Collection for the items
$menuCollection = collect($menuArray);
// group the Collection on the menutype field
$groupedMenu = $menuCollection->groupBy('menutype');
/**
* Note that Eloquent queries (using Models) will automatically return
* Collections, so if you have your Menu model setup, your first two
* lines would just be:
* $menuCollection = Menu::get();
* or, all three lines could be combined into:
* $groupedMenu = Menu::get()->groupBy('menutype');
*/
// pass the grouped Collection to the view
return view('guest.menu')->with('data', $groupedMenu);
}
Now, in your view, your outer foreach will iterate through the groups. The inner foreach will iterate through the items in each group:
<div class="row">
#foreach($data as $type => $items)
<div class="col-1-3">
<div class="wrap-col">
<h3>{{$type}}</h3>
#foreach($items as $item)
<div class="post">
<img src="assets/images/{{$item->itemimage}}"/>
<div class="wrapper">
<h5>{{$item->itemname}}</h5>
<span>Rs.{{$item->itemprice}}/-</span>
</div>
</div>
#endforeach
</div>
</div>
#endforeach
</div>

Making dynamic pages from DB with Laravel

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);
}

Categories