Slug not work properly - php

I am try create slug with laravel on admin its work but on front-end view its work too except one problem, i have four article and work nice on admin but when on view front end its always open same article even-tough slug is different URL.
Controller code
public function singleArticle($slug){
Article::where('slug', '=', $slug)->increment('viewed');
$navi['country'] = Country::get();
$navi['genre'] = Genre::get();
$articles = Article::orderBy('created_at','desc')->limit(3)->get();
$latest_movies = Movie::where('type', '=', 'movie')->orderBy('created_at','desc')->limit(4)->get();
$latest_tv = Movie::where('type', '=', 'tv')->orderBy('created_at','desc')->limit(4)->get();
$most_viewed_movies = Movie::where('type', '=', 'movie')->orderBy('viewed','desc')->limit(3)->get();
$most_viewed_tv = Movie::where('type', '=', 'tv')->orderBy('viewed','desc')->limit(4)->get();
$most_viewed_article = Article::orderBy('created_at','desc')->orderBy('viewed','desc')->limit(4)->get();
$article = Article::where('slug', '=', $slug)->first();
and for view front end
#if(count($articles) > 0)
<div class="articles_list">
#foreach($articles as $article)
<div class="col-md-6">
<div class="article_item row">
<div class="article_info">
#if($article->thumb)
<a href="{{route('articles.single',$article->slug)}}"><img class="img-responsive" src="{{ url(Image::url($article->thumb,350,200,array('crop'))) }}" alt="{{$article->title}}">
#else
{{-- <img class="img-responsive" src="{{ url(Image::url($article->thumb,250,250,array('crop'))) }}" alt="{{$article->title}}"> --}}
#endif
<div class="artice_title"><h3>{{$article->title}}</h3></div>
<div class="article_time">
<span class="author">By Admin</span>
<span class="cateogry">Category</span>
<span class="time">{{date('F d, Y', strtotime($article->created_at))}} </a></span></div>
<!--<div class="article_descr">
<?php echo mb_substr($article->content, 0, 200) . ' ...'; ?>
</div>
<a class="btn btn-default read_more" href="{{route('articles.single',$article->id)}}">Read more</a> -->
</div>
</div>
</div>
#endforeach
</div>
<div class="clearfix"></div>
<div class="text-center col-xs-12">
{{$articles->links()}}
</div>
#else
<div class="col-xs-12">
Nothing found in there
</div>
#endif
For routing below code :
// Category
Route::get('category/{slug}', ['as' => 'category.index', 'uses' => 'CommonController#categoryIndex']);
// Articles
Route::get('articles', ['as' => 'articles.index', 'uses' => 'CommonController#articleIndex']);
// Specific article
Route::get('articles/{slug}', ['as' => 'articles.single', 'uses' => 'CommonController#singleArticle']);
thanks before.

It is just issue of naming convention.Please choose different names for variables.
#foreach($articles as **$article**). It is in your view which have $article variable.
**$article** = Article::where('slug', '=', $slug)->first(); It is in your controller. so it is just because of conflict.

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

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

ErrorException Undefined variable when trying to show data in view

So i was trying to display a record from a database with laravel, and i have defined the variable in #foreach statement but when i run it it shows ErrorException Undefined variable , although all variable already inside the foreach statement, am i missing a method function in my controller?
this is the view
welcome.blade.php
<div class="blog-item">
<div class="blog-text text-box text-white">
#foreach ($guestbooks as $guestbook)
<div class="top-meta">{{ Carbon\Carbon::parse($guestbook->created_at)->format('d-m-Y') }} / di Rakitan</div>
<h3>{{ $guestbooks->name }}</h3>
<p>{!! \Illuminate\Support\Str::words($guestbook->message, 50, '...') !!}</p>
Lanjutkan Baca <img src="asset/img/icons/double-arrow.png" alt="#"/>
</div>
</div>
<!-- Blog item -->
<div class="blog-item">
<div class="blog-text text-box text-white">
<div class="top-meta">{{ Carbon\Carbon::parse($guestbook->created_at)->format('d-m-Y') }} / di Rakitan</div>
<h3>{{ $guestbook->name }}</h3>
<p>{!! \Illuminate\Support\Str::words($guestbook->message, 50, '...') !!}</p>
Lanjutkan Baca <img src="asset/img/icons/double-arrow.png" alt="#"/>
</div>
</div>
<!-- Blog item -->
<div class="blog-item">
<div class="blog-text text-box text-white">
<div class="top-meta">{{ Carbon\Carbon::parse($guestbook->created_at)->format('d-m-Y') }} / di Rakitan</div>
<h3>{{ $guestbook->name }}</h3>
<p>{!! \Illuminate\Support\Str::words($guestbook->message, 50, '...') !!}</p>
Lanjutkan Baca <img src="asset/img/icons/double-arrow.png" alt="#"/>
#endforeach
</div>
</div>
this is the controller
GuestbookController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Guestbook;
class GuestbookController extends Controller
{
public function index()
{
$guestbooks = Guestbook::get();
return view('post.post_textarea',[
'guestbooks' => $guestbooks
]);
}
public function store(Request $request)
{
Guestbook::create([
'name' => $request->name,
'message' => $request->message
]);
return redirect()->back();
}
}
and this is the routes
Route::get('/posting','GuestbookController#index')->name('guestbook');
Route::post('/posting','GuestbookController#store')->name('guestbook.store');
Your GuestbookController function index() is returning a view called post.post_textarea and passing your $guestbook variable to that view, while you are trying to get that variable in your welcome.blade.php.
Change your index function to return welcome view like this:
public function index()
{
$guestbooks = Guestbook::get();
return view('welcome',[
'guestbooks' => $guestbooks
]);
}
i figured the problem was that there are two routes routing into the same url as Route::get('/posting','GuestbookController#index')->name('guestbook'); so i delete the other one and it works thanks about that typo tough #Denis Ćerić

Laravel 5.7 Comment count for different posts

I am stucked at point where i got comment count for posts but it shows count of all comments of all posts on every post. I would like to know how to output in blade comment count for post ID
here is controller:
$posts = $posts->orderBy("posted_at", "desc")
->paginate(config("blogetc.per_page", 10));
$comments = BlogEtcComment::all();
return view("blogetc::index", [
'posts' => $posts,
'title' => $title,
'comments' => $comments,
]);
blade:
#foreach($posts as $post)
<section class="blog_area p_120">
<div class="container">
<div class="row">
<div class="col-lg-8">
<div class="blog_left_sidebar">
<article class="blog_style1">
<div class="blog_img">
<img class="img-fluid" src="blog_images/{{$post->image_large}}" alt="">
</div>
<div class="blog_text">
<div class="blog_text_inner">
<div class="cat">
<a class="cat_btn" href="{{$post->url()}}">{{$post->slug}}</a>
<i class="fa fa-calendar" aria-hidden="true"></i>{{$post->created_at}}
<i class="fa fa-comments-o" aria-hidden="true"></i> {{count($comments)}}
</div>
<h4>{{$post->title}}</h4>
<p>{!! $post->generate_introduction(400) !!}</p>
<a class="blog_btn" href="{{$post->url()}}">Lasīt vairāk</a>
</div>
</div>
</article>
</div>
</div>
</div>
</div>
</section>
#endforeach
//Quickfix:
//assuming your posts table is called posts and that in your blogetccomments table //you have a post_id column pointing to the original post. Try something like
$posts = DB::table('posts')
->leftJoin('blogetccomments', 'posts.id', '=', 'blogetccomments.post_id')
->selectRaw('posts.*, count(blogetccomments.post_id) as commentcount')
->groupBy('posts.id')
->get();
In your blade template, Access the comments count for each post, as follows..
#foreach($posts as $post)
...
{{$post->title}}...
{{$post->commentcount}}
...
#endforeach
You can use withCount() to get count of comments for a specific post :
$posts = $posts->withCount('comments')
->orderBy("posted_at", "desc")
->paginate(config("blogetc.per_page", 10));
Above would require you to have comments relation on your Post Model :
Post Model :
public function comments()
{
return $this->hasMany(BlogEtcComment::class);
}
BlogEtcComment Model :
public function post()
{
return $this->belongsTo(Post::class);
}
And then in blade :
#foreach($posts as $post)
<p>Post : $post->id</p>
<p>Comments : $post->comments_count</p>
#endforeach

Laravel get profile name

I'm laravel newbie and I'm making simple CMS. So i have simple question:
I wan't when click on avatar - redirect to user profile (http://example.com/profiles/nickname/id)
In DB it saves that:
as you see author_id I have, now I need to get author name from users table:
And then generate url: http://example.com/profiles/Evaldas/2 (Evaldas, because author_id is 2 in topics table)
My routes file:
Route::get('topic/{tname}/{tid}', 'viewTopic#showTopic');
My viewTopic.php Controller:
<?php
namespace App\Http\Controllers;
use DB;
use View;
class viewTopic extends Controller
{
public function showTopic($tname, $tid)
{
return View::make('posts', [
'topics' => DB::table('topics')
->where('id', $tid)
->where('seo_title', $tname)
->first(),
'posts' => DB::table('posts')
->where('topic_id', $tid)
->select()
->get()
]);
}
}
And layout:
#extends('layouts.main')
#section('content')
<div class="media">
<div class="media-left">
<a href="HERE MUST BE HREF TO PROFILE">
<img class="media-object" src="http://localhost/uploads/avatars/2.jpg" style="width: 64px">
</a>
</div>
<div class="media-body" rel="#author{{ $topics->author_id }}">
<h4 class="media-heading">{{ $topics->title }}</h4>
#if(!empty($topics->text))
{{ $topics->text }}
#else
Message empty :(
#endif
</div>
#foreach($posts as $post)
<div class="media">
<div class="media-left">
<a href="HERE MUST BE HREF TO PROFILE">
<img class="media-object" src="http://localhost/uploads/avatars/1.png" style="width: 64px">
</a>
</div>
<div class="media-body" rel="#post{{ $post->pid }}">
{{ $post->text }}
</div>
</div>
#endforeach
</div>
#stop
Thanks so much in advance :)
If you want to use the Query Builder, you can use the join() method:
DB::table('posts')
->where('topic_id', $tid)
->join('users', 'user.id', '=', 'posts.author_id')
->select()
->get()
This way, the user information will be available:
$post->nickname
You can then build your URL using a laravel helper, for exemple, if you have a profile route:
<a href="{{route('profile', ['nickname' => $post->nickname, 'id' => $post->author_id]);}}">
An other method is to create models for your tables and define relationship between them.
See this: http://laravel.com/docs/5.1/eloquent-relationships
Using this method, you will be able to write things like $post->author->nickname

Categories