Laravel db contents not displaying - php

I have 2 variables pulled from my DB $month and $id. When i do $if(isset($slug)) if queries the db and displays the results. When i do the same for $month it doesn't output anything but will load the page. I can't see anything wrong with the code as it all matches??
routes.php
Route::get('blog/{id}', ['as' => 'blog.id', 'uses' => 'BlogController#ShowbyId']);
Route::get('blog/{month}', ['as' => 'blog.month', 'uses' => 'BlogController#ShowbyMonth']);
<?php class BlogController extends BaseController {
public function ShowAll() {
$blogs = Blog::all();
$blogs = DB::table('blogs')->paginate(3);
return View::make('pages.blog')
->with('blogs', $blogs);
}
public function ShowById($id) {
$ids = Blog::where('id', $id)
->get();
return View::make('pages.blog')
->with('ids', $ids);
}
public function ShowByMonth($month) {
$months = Blog::where('month', $month);
$months = DB::table('blogs')->paginate(3);
return View::make('pages.blog')
->with('months', $months);
}
}
blog.blade.php
#if(isset($blogs))
#foreach ($blogs as $blog)
<div class="blog-outer-wrap">
<img src="images/blog/{{ $blog->img}}">
<div class="blog-header">{{ $blog->header }}</div>
<div class="blog-text">{{ $blog->content }}</div>
<a href="{{ URL::route('blog.id', [$blog->id]) }}"><div class="blog-readmore">Read More</div>
</div>
#endforeach
#elseif(isset($ids))
#foreach ($ids as $id)
<div class="blog-outer-wrap">
<img src="../images/blog/{{ $id->img}}">
<div class="blog-header">{{ $id->header }}</div>
<div class="blog-text">{{ $id->content }}</div>
</div>
#endforeach
#elseif(isset($months))
#foreach ($months as $month)
<div class="blog-outer-wrap">
<img src="images/blog/{{ $month->img}}">
<div class="blog-header">{{ $month->header }}</div>
<div class="blog-text">{{ $month->content }}</div>
<a href="{{ URL::route('blog.month', [$month->slug]) }}"><div class="blog-readmore">Read
</div>
#endforeach
#endif

Since I can't comment I'll post as an answer.
Your two routes:
Route::get('blog/{id}', . . . );
Route::get('blog/{month}', . . . );
Are the same, any uri blog/whatever will hit the first Route no matter what, the second one will never get hit because the first wildcard {id} will take any argument. So you are always hitting BlogController#ShowById
So i'm guessing your passing in month to try and hit the ShowByMonth controller. Instead it's routing you to:
public function ShowById($id) {
$ids = Blog::where('id', $id)
->get();
return View::make('pages.blog')
->with('ids', $ids);
}
Where your query becomes Blog::where('id', 'January'); or whatever month you put into your uri.
Fix:
Add constraints
Route::get('blog/{id}', [
'as' => 'blog.id',
'uses' => 'BlogController#ShowbyId']
)->where('id', '[0-9]+'); // Only if {id} is any integer
Route::get('blog/{month}', [
'as' => 'blog.month',
'uses' => 'BlogController#ShowbyMonth']
)->where('month', '[A-Za-z]+'); // Only if {month} is any alpha character

Related

routes/web route me to another route

My web doesn't seem to be directing to the correct page.
Here is my blade
<div class="container">
<div class="col-lg-12 d-flex justify-content-between align-items-center">
<h2>Informations</h2>
<a href="{{ route('add-new-information') }}" class="btn text-success">
<i class="fas fa-plus-circle fa-2x"></i>
</a>
</div>
<hr>
<div class="row d-flex justify-content-center align-items-center mt-5" style="max-height: 500px !important; overflow-y: scroll">
#foreach ($informations as $info)
<div class="card col-sm-11 p-0 mb-4 clickable-item" onclick='window.location = "{{ route('admin-informations', ['id' => $info->id]) }}"'>
...
</div>
#endforeach
</div>
</div>
Here is my routes/web
Auth::routes();
Route::group(['middleware' => ['auth'], 'prefix' => '/',], function () {
Route::get('/', function () {
return redirect('/home');
});
Route::group(['prefix' => 'admin'], function() {
Route::get('/informations', [App\Http\Controllers\InformationController::class, 'index'])->name('informations');
Route::get('/informations/{id}', [App\Http\Controllers\InformationController::class, 'indexAdminInfo'])->name('admin-informations');
Route::get('/informations/add-new-information', [App\Http\Controllers\InformationController::class, 'add'])->name('add-new-information');
});
});
and here is my controller
public function indexAdminInfo($id){
$information = Information::find($id);
// $comments = Comment::where('information_id', $id)->orderByDesc('created_at')->get();
$ack_count = Acknowledge::where('information_id', $id)->count();
$user_ack = Acknowledge::where([
['information_id', '=', $id],
['user_id', '=', Auth::user()->id],
])->first();
$ack = 'FALSE';
if($user_ack != null){
$ack = 'TRUE';
}
return view('adminviews/infoadmin', compact('information', 'ack_count', 'ack', 'user_ack'));
}
public function add(){
return view('adminviews/addinfo');
}
For some reason, when I click the a tag with the href {{ route('add-new-information') }} to go to the add page 'adminviews/addinfo',
instead the page will go to the 'adminviews/infoadmin' page, which will cause an error, because no parameters are being sent.
I tried checking the code, but it looks correct to me. Can anybody find an error on this?
the problem is with your routes:
these two routes are ambiguous:
Route::get('/informations/{id}');
Route::get('/informations/add-new-information');
just think of below scenario:
router wants to route, this url : /information/add-new-information
router will hit the first defined route, because it is compatible with the definition ('/informations/{id}')
Note :{id} is a variable and can be any string
so it will go with this.
Solution
write the more restricted route first,
and more general route later:
Route::get('/informations/add-new-information');
Route::get('/informations/{id}');

Display posts belonging to category in laravel

I am trying to get the posts that belong to each category, i had this working before but i can't seem to find what i have done wrong here.
I have a Post Table and a Categories Table
ROUTE
Route::get('articles/category/{id}', ['as' => 'post.category', 'uses' => 'ArticlesController#getPostCategory']);
CONTROLLER
public function getPostCategory($id)
{
$postCategories = PostCategory::with('posts')
->where('post_category_id', '=', $id)
->first();
$categories = PostCategory::all();
// return view
return view('categories.categoriesposts')->with('postCategories', $postCategories)->with('categories', $categories);
}
VIEW
#foreach($postCategories->posts as $post)
<div class="well">
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="http://placekitten.com/150/150">
</a>
<div class="media-body">
<h4 class="media-heading">{{ substr($post->title, 0, 50) }}</h4>
<p class="text-right">By Francisco</p>
<p>{{ substr($post->body, 0, 90) }}</p>
<ul class="list-inline list-unstyled">
</ul>
</div>
</div>
</div>
#endforeach
POST MODAL
public function postCategory()
{
return $this->belongsTo('App\PostCategory');
}
POSTCATEGORY MODAL
class PostCategory extends Model
{
// connect Categories to Posts tables
protected $table = 'post_categories';
// Category belongs to more than 1 post
public function posts()
{
return $this->hasMany('App\Post', 'post_category_id');
}
}
I can't see what i am doing wrong every time I go to a category it shows
Trying to get property of non-object
Any help will be much appreciated thanks
replace your lines:
$postCategories = PostCategory::with('posts')
->where('post_category_id', '=', $id)
->first();
with:
$postCategories = PostCategory::find($id)->posts;
Change your line in your PostCategoryModel to:
return $this->hasMany('App\Post', 'post_category_id','post_category_id');

Route not[discussion] defined

This is my route.
Route::get('discussion/{slug}',[
'use' => 'DiscussionsController#show',
'as' => 'discussion.show'
]);
This is show function
public function show($slug)
{
$discussion = Discussion::where('slug', $slug)->first();
return view('discussions.show', compact('discussion'));
}
i am getting this error.
view file like this
#section('content')
<div class="card">
<div class="card-header">{{$discussion->tittle}}</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
</div>
</div>
#endsection
here i call redirect the route, and get the error
$discussion = Discussion::create([
'tittle' => $request->title,
'content' => $request->contant,
'chanel_id' => $request->channel_id,
'user_id' => Auth::id(),
'slug' => str_slug($request->title)
]);
return redirect()->route('discussion', ['slug' => $discussion->slug]);
ERR_MSG:
Route
Route::get('discussion/{slug}',['as'=>'discussion.show','use'=>'DiscussionsController#show']);
Controller
public function show($slug){
$discussion = Discussion::where('slug', $slug)->first();
return view('discuss', compact('discussion'));
}
Your blade file must be discuss.blade.php
You are going to use that discussion.show if you only need something like this on your view page
View Slug

NotFoundHttpException in RouteCollection.php line 161 - Laravel 5.2

I cant make this route works
routes.php:
Route::get('/home/category/{$category_id}', 'HomeController#category');
HomeController.php
public function category(Request $request, $category_name, $category_id)
{
$listProject = $this->project->getProjectsFromCategory($category_id);
return view('category', [
'projects' => $listProject,
]);
}
view
<div class="col-md-12">
#foreach ($categories as $key => $cat)
{{ $cat->name }}
#endforeach
</div>
url in browser
http://localhost:8888/ko/public/home/category/6
and i'm getting
NotFoundHttpException in RouteCollection.php line 161
Does anyone see something wrong ?
I have another route which is working
Route::get('/home/project/{project_id}','ProjectDetailsController#index');
Thanks for help
here is more code
routes.php
Route::auth();
Route::get('/', 'HomeController#index');
Route::get('/home', 'HomeController#index');
Route::get('/home/project/{project_id}','ProjectDetailsController#index');
Route::post('/home/create/addProject', 'CreateController#addProject');
Route::get('/home/create', 'CreateController#index');
Route::get('/home/category/{$category_id}', 'HomeController#category');
HomeController.php
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct(ProjectRepository $project, UserRepository $user, CategoryRepository $category)
{
//$this->middleware('auth');
$this->project = $project;
$this->user = $user;
$this->category = $category;
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$listProject = $this->project->getAllProjects();
$categories = $this->category->getAllCategories();
foreach($listProject as $key => $project){
// get creator of project
$user[$key] = $this->user->getCreator($project->creator_id);
// get category of project
$category[$key] = $this->category->getCategory($project->category_id);
}
return view('home', [
'projects' => $listProject,
'user' => $user,
'category' => $category,
'categories' => $categories
]);
}
public function category(Request $request, $category_id)
{
$listProject = $this->project->getProjectsFromCategory($category_id);
return view('category', [
'projects' => $listProject,
]);
}
}
view
#extends('layouts.app')
#section('content')
<div class="container-fluid">
<div class="row">
#foreach ($projects as $key => $project)
<div class="col-md-4" style='margin-bottom:20px;'>
<div class="border" style="border:1px solid #e7e7e7; padding:15px;">
ID : {{ $project->id }} <br>
TITLE : {{ $project->title }} <br>
CATEGORY : {{ $category[$key]->name }} <br>
CREATOR : {{ $user[$key]->name }} <br> <br>
DETAILS : See project
</div>
</div>
#endforeach
</div>
<div class="row">
<div class="col-md-12">
#foreach ($categories as $key => $cat)
{{ $cat->name }}
#endforeach
</div>
</div>
</div>
#endsection
Your controller is wrong. You send to controller from route only 1 parameter ($category_id). But accept another parameter: $category_name in your controller.
Removing $category_name from controller will fix an error.
You need just define only parameters from route in your controller. /category is not a parameter.
Documentation
Also there is a wrong code in your blade file:
Replace
{{ $cat->name }}
With
<a href='{{url("home/category/$cat->id")}}'> {{ $cat->name }} </a>

Lavravel route url not displaying correct results from db

I'm trying to pass the getMonth view via the route but doens't seem be working as it shows all results from my db when the $month is specified instead of filtering the results by month. However $id does work and will go to a single post matching the $id from the db.
Route::get('blog', ['as' => 'blog', 'uses' => 'BlogController#BlogIndex']);
Route::get('blog/{Id}', ['as' => 'blog.id', 'uses' => 'BlogController#ShowbyId']);
Route::get('blog/month/{month}', ['as' => 'blog.month', 'uses' => 'BlogController#ShowbyMonth']);
class BlogController extends BaseController {
public function BlogIndex()
{
//get the posts from the database by asking the Active Record for "all"
$blogs = Blog::all();
$blogs = DB::table('blogs')->paginate(3);
// and create a view which we return - note dot syntax to go into folder
return View::make('pages.blog', array('blogs' => $blogs));
}
public function ShowbyId($Id)
{
$Ids = Blog::where('Id', '=', $Id)->get();
// show the view with blog posts (app/views/pages/blog.blade.php)
return View::make('pages.blog')
->with('Ids', $Ids)
}
public function ShowbyMonth($month)
{
$months = Blog::where('month', '=', $month)->get();
// show the view with blog posts (app/views/pages/blog.blade.php)
return View::make('pages.blog')
->with('months', $months)
}
}
blog.blade.php
#if(isset($blogs))
#foreach ($blogs as $blog)
<div class="blog-outer-wrap">
<img src="images/blog/{{ $blog->img}}">
<div class="blog-header">{{ $blog->header }}</div>
<div class="blog-text">{{ $blog->content }}</div>
<a href="{{ URL::route('blog.slug', [$blog->slug]) }}">
</div>
#endforeach
#elseif(isset($Ids))
#foreach ($Ids as $Id)
<div class="blog-outer-wrap">
<img src="images/blog/{{ $Id->img}}">
<div class="blog-header">{{ $Id->header }}</div>
<div class="blog-text">{{ $Id->content }}</div>
</div>
#elseif(isset($months))
#foreach ($months as $month)
<div class="blog-outer-wrap">
<img src="images/blog/{{ $Month->img}}">
<div class="blog-header">{{ $Month->header }}</div>
<div class="blog-text">{{ $Month->content }}</div>
</div>
#endif
#endforeach
I'm not sure if it solves the problem but in blade file you have:
#elseif(isset($months))
#foreach ($months as $month)
<div class="blog-outer-wrap">
<img src="images/blog/{{ $Month->img}}">
<div class="blog-header">{{ $Month->header }}</div>
<div class="blog-text">{{ $Month->content }}</div>
</div>
#endif
and it should be rather:
#elseif(isset($months))
#foreach ($months as $Month)
<div class="blog-outer-wrap">
<img src="images/blog/{{ $Month->img}}">
<div class="blog-header">{{ $Month->header }}</div>
<div class="blog-text">{{ $Month->content }}</div>
</div>
#endif
You should care about variables case.
The problem I see is your URI/route structure, you currently have this:
Route::get('blog/{Id}', ['as' => 'blog.id', 'uses' => 'BlogController#ShowbyId']);
Route::get('blog/month/{month}', ['as' => 'blog.month', 'uses' => 'BlogController#ShowbyMonth']);
Whenever you try to access the blog.month route blog.id is receiving the word month. It may be better to put the month route first, so that the month URI is hit before the ID route.
Route::get('blog/month/{month}', ['as' => 'blog.month', 'uses' => 'BlogController#ShowbyMonth']);
Route::get('blog/{id}', ['as' => 'blog.id', 'uses' => 'BlogController#ShowbyId']);
Also, to clean up your controller you may consider using a query scope to make your logic more reusable and easier to debug. In your model you could do something like this:
class Blog extends Eloquent {
public function scopeMonth($query, $month) {
return $query->where('month', '=', $month);
}
}
Then in your Controller you could do this:
class BlogController extends BaseController {
//.. BlogIndex here
public function ShowbyId($Id)
{
$blog = Blog::find($id)->get();
// show the view with blog posts (app/views/pages/blog.blade.php)
return View::make('pages.blog')
->with('Ids', $blog);
}
public function ShowbyMonth($month)
{
$months = Blog::month($month)->get();
// show the view with blog posts (app/views/pages/blog.blade.php)
return View::make('pages.blog')
->with('months', $months)
}
}
Hopefully this helps!

Categories