How Would I Send Data To a Controller - php

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.

Related

Attempt to read property "ticket_title" on bool

I have this problem when I want to open specific page by id.
now I am trying to shown title on my page with specific id, which have post in db, but that error stopped me.
there are my code.
route
Route::get('/tickets/{id}', [TicketsController::class, 'show'])->name('tickets.show');
controller
public function show($id) {
$tickets = Tickets::with('companies')->get();
$ticketscomp = Companies::with('tickets')->get();
$severities = Severities::with('tickets')->get();
$ticketspage = Tickets::findOrFail($id);
return view('tickets.chat', compact('ticketspage'))->with(['tickets'=> $tickets])->with(['ticketscomp'=>$ticketscomp])->with(['severities'=>$severities])->with(['ticketspage'=>$ticketspage]);
//dd($ticketspage->toArray());
blade.php
#foreach ($ticketspage as $item)
<h6 class="mb-1; ticket-list-title;">{{ $item->ticket_title }}</h6>
#endforeach
When I dd post. post is opening by id with included information.
::findOrFail() returns a single model instance. You do not need a #foreach() loop.
<h6 class="mb-1; ticket-list-title;">{{ $ticketspage->ticket_title }}</h6>
I fix this now but if someone have problem like me just read my comment.
Just remove foreach and type like this
<h6 class="mb-1; ticket-list-title;">{{ $ticketspage->ticket_title }}</h6>

create counter for blog categories in laravel

I´m traying to create one counter for my blog´s categories. This should appear to the right name side of my category . i´m using my model with variable appends, that after i will use in my blade for show my result in one span. But i don´t know very well how i can use count in my Model. I´m doing this in my model Blog.
my variable appends contain:
protected $appends = [
'custom_fields',
'has_media',
'restaurant',
'blog_category',
'viewer',
'postCounter',
];
i´m traying this:
return $this->blogs()->count();
i have a relation between blog and blog_category with:
public function blogCategory()
{
return $this->belongsTo(\App\Models\BlogCategory::class, 'blog_category_id', 'id');
}
i want to do in my view appear for example:
innovation (2)
in my view i´m doing this:
#foreach($categories as $category)
<li>{{ trans('web.blog_category_'.$category->name) }}<span>{{$category->postCounter}}</span></li>
#endforeach
but always returned me 0, and i have post with categories
updated
With laravel relationship withCount you can do this easily. If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models.
add withCount method to your query
$categories = Category::withCount('blogCategory')->get();
You can access the count in your foreach loop
// $category->blogCategory_count
#foreach($categories as $category)
<li>
<a href="{{ url('blogs/'.$category->name) }}">
{{trans('web.blog_category_'.$category->name) }}
</a>
<span>{{$category->blogCategory_count}}</span>
</li>
#endforeach

how to show multiple category name from checkbox value in eloquent relationship laravel

firstly, i'm a newbie in laravel.
i insert a array data as a string in server.
column name "category_id" & value like "1,2,3,4".
Now i just want to show these id's category name with eloquent relationship.
Using laravel latest version.
view page
{{$category_var = explode(',',$post->category_id)}}
#foreach($category_var as $category)
#if($category)
<span class="badge mb-3">{{$post->category->category}} </span>
#endif
#endforeach
class page
public function category(){
return $this-> belongsTo(Category::class);
}
Controller page
public function index()
{
$posts = post::paginate(9);
return view('pages/home',compact('posts'));
}
anything else need just ask me.
Thanks
just use the benefits of models and relation like below:
#foreach($posts as $post)
#foreach($post->category as $category)
<span class="badge mb-3">
{{ $category->(what ever you want from category model) }}
</span>
#endforeach
#endforeach

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.

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