Lavravel route url not displaying correct results from db - php

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!

Related

laravel view doesn't show data after adding new route

It works really good, but when I've created new page something goes wrong and now my blog view doesn't show data, but blogs view still correctly show data . I am trying to show detailed data of each blog when user click on button "Details"
MainController:
public function blog(Blogs $blog)
{
return view('blog', compact('blog'));
}
public function blogs()
{
return view('blogs',['blogs' => Blogs::all(),]);
}
blogs.blade.php:
#extends('layouts.master')
#section('title', __('main.blogs'))
#section('content')
<div class="row">
#foreach($blogs as $blog)
#include('layouts.cardBlog', compact('blog'))
#endforeach
</div>
#endsection
and cardBlog.blade.php:
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="{{($blog->image) }}">
<div class="caption">
<h3>{{ $blog->title }}</h3>
<p>{{ $blog->body }}</p>
<p>
<a href="{{route('blog', $blog->id) }}"
class="btn btn-default"
role="button">#lang('main.more')</a>
#csrf
</p>
</div>
</div>
</div>
blog.blade.php
#extends('layouts.master')
#section('title', __('main.blogs'))
#section('content')
<h1>{{ $blog->title}}</h1>
<img src="{{$blog->image }}">
<p>{{ $blog->body }}</p>
#endsection
web.php:
Route::get('/', 'MainController#index')->name('index');
Route::get('/categories', 'MainController#categories')->name('categories');
Route::get('/about', 'MainController#aboutus')->name('about');
Route::get('/contact-us', 'ContactUSController#contactUS')->name('contact-us');
Route::post('contactus', ['as'=>'contactus.store','uses'=>'ContactUSController#contactSaveData']);
Route::get('/contacts', 'MainController#contacts')->name('contacts');
Route::get('/blogs', 'MainController#blogs')->name('blogs');
Route::get('/blog/{id}', 'MainController#blog')->name('blog');
Route::get('/intership', 'MainController#intership')->name('intership');
Route::get('/{category}', 'MainController#category')->name('category');
Route::get('/{category}/{product}/{skus}', 'MainController#sku')->name('sku');
Route::post('subscription/{skus}', 'MainController#subscribe')->name('subscription');
What's is the error that it shown?
I suggest use "compact" in this line code
return view('blogs',['blogs' => Blogs::all(),]);
Something like this
public function blogs()
{
$blogs = Blogs::all();
return view('blogs',compact('blogs'));
}
Try this
public function blog($id)
{
$blog = Blogs::findOrFail($id)
return view('blog', compact('blog'));
}

LARAVEL 7 - How to pass variables to views

I have two tables, Companies and Projects. A company hasMany projects and a project belongsTo a company.
Company.php model
protected $fillable = [
'id', 'name', 'description'
];
public function projects()
{
return $this->hasMany('App/Project');
}
Project.php model
protected $fillable = [
'name', 'description', 'company_id', 'days'
];
public function company()
{
return $this->belongsTo('App/Company');
}
From my index.blade.php, I list the companies only and I have made them clickable so that when a user clicks on a company listed, they are taken to show.blade.php where the name of the company and the projects that belong to that company are displayed like so.
<div class="jumbotron">
<h1>{{ $company->name }}</h1>
<p class="lead">{{ $company->description }}</p>
</div>
<div class="row">
#foreach($company->projects as $project)
<div class="col-lg-4">
<h2>{{ $project->name }}</h2>
<p class="text-danger">{{ $project->description }}</p>
<p><a class="btn btn-primary" href="/projects/{{ $project->id }}" role="button">View Projects »</a></p>
</div>
#endforeach
</div>
Now am getting an undefined variable $project error. So I decided to declare variable in my show() function of the CompaniesController.php like so
public function show(Company $company)
{
$company = Company::find($company->id);
$projects = Company::find(1)->projects;
return view('companies.show', ['company' => $company, 'projects' => $projects]);
}
And access variable in show.blade.php like so
<div class="jumbotron">
<h1>{{ $company->name }}</h1>
<p class="lead">{{ $company->description }}</p>
</div>
<div class="row">
#foreach($projects as $project)
<div class="col-lg-4">
<h2>{{ $project->name }}</h2>
<p class="text-danger">{{ $project->description }}</p>
<p><a class="btn btn-primary" href="/projects/{{ $project->id }}" role="button">View Projects »</a></p>
</div>
#endforeach
</div>
Now am getting a Class 'App/Project' not found error when I access show.blade.php. I am having a challenge passing company projects to the view. Any help will be appreciated. Here are my routes;
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('companies', 'CompaniesController');
Route::resource('projects', 'ProjectsController');
I would be hilarious if I am right....
In your models where defining relations replace App/Project with App\Project. Do the same for Company.... Replace "/" with "\".
You have to namespace Project class properly
Make sure file name is Project.php
Make sure inside Project.php namespace declaration is correct: namespace App;
Make sure class name inside Project.php is 'Project' : class Project extends Model { ...
Make sure you have imported it in controller. use App\Project
After all that done you will not get error:
Class 'App/Project' not found
You have correctly done passing variable in view but have a look here for another examples and methods passing about it:
https://laravel.com/docs/7.x/views
Hope this helps you
You're already using model binding. In your show method, you do not need to find. just return what you need
public function show(Company $company)
{
return view('companies.show', ['company' => $company];
}
In your view, you can then do:
#foreach($company->projects as $project)
...
#endforeach

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

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>

Laravel db contents not displaying

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

Categories