I'm a new developer and I'm trying to make work my very simple blog.
I want to set a previous and a next link to my previous and next articles in the blog. This is my current code.
POSTS CONTROLLER
public function move($id)
{
$post = DB::table('posts')->find($id);
$previous = DB::table('posts')->where('id', '<', $post->id)->max('id');
$next = DB::table('posts')->where('id', '>', $post->id)->min('id');
return view('posts.show')->with('previous', $previous)->with('next', $next);
}
WEB.PHP
<?php
Route::get('/', 'PostsController#index')->name('home');
Route::get('/posts/create', 'PostsController#create');
Route::post('/posts', 'PostsController#store');
//Route::get('/posts/{post}', 'PostsController#show');
Route::get('/posts/tags/{tag}', 'TagsController#index');
Route::post('/posts/{post}/comments','CommentsController#store');
Route::get('/posts/{id}/edit', 'PostsController#edit');
Route::get('/edit/{post}', 'PostsController#update');
Route::patch('/post/{post}', 'PostsController#update');
Route::get('/register', 'RegistrationController#create');
Route::post('/register', 'RegistrationController#store');
Route::get('/login', 'SessionsController#create');
Route::post('/login', 'SessionsController#store');
Route::get('/logout', 'SessionsController#destroy');
Route::get('/posts/{id}', 'PostsController#move');
SHOW.BLADE
#extends ('layouts.master')
#section ('content')
<div class="col-sm-8 blog-main">
<h1> {{$post->title}}</h1>
#if (count($post->tags))
<ul>
#foreach($post->tags as $tag)
<li>
<a href="/posts/tags/{{ $tag->name}}">
{{ $tag->name }}
</a>
</li>
#endforeach
</ul>
#endif
{{$post->body}}
<hr>
Modifica
<hr>
<div class='comments'>
<ul class="list-group">
#foreach ($post->comments as $comment)
<li class="lista-commenti">
<strong>
{{$comment->created_at->diffForHumans()}}:
</strong>
{{ $comment -> body}}
</li>
#endforeach
</ul>
</div>
<hr>
<div>
<div>
<form method="POST" action="/posts/{{$post->id}}/comments">
{{csrf_field()}}
<div>
<textarea name="body" placeholder="Il tuo commento" class="form-control" required></textarea>
</div>
<div>
<button type="submit" class="bottone">Invia Commento</button>
</div>
</form>
#include('layouts.errors')
</div>
<div class="row">
<ul>
<li> Previous</li>
<li> Next
</li>
</ul>
</div>
</div>
</div>
#endsection
POST.PHP
<?php
namespace App;
use Carbon\Carbon;
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function addComment($body)
{
$user_id= auth()->id();
$this->comments()->create(compact('user_id','body'));
}
public function scopeFilter($query, $filters)
{
if(!$filters)
{
return $query;
}
if ($month = $filters['month'])
{
$query->whereMonth('created_at', Carbon::parse($month)->month);
}
if ($year = $filters['year']) {
$query->whereYear('created_at', $year);
}
}
public static function archives()
{
return static::selectRaw('year(created_at) year, monthname(created_at) month, count(*) published')
->groupBy('year','month')
->orderByRaw('min(created_at) desc')
->get()
->toArray();
}
public function tags(){
return $this->belongsToMany(Tag::class);
}
}
This gives me an error about the undefined variables previous and next and also about the www.
Sorry but this is my first post and I can't upload any images. Hope someone can help me.
Thanks
Alessandro
use url() helper method:
<li> Previous</li>
<li> Next</li>
Edit: remove this Route::get('/posts/{post}', 'PostsController#show'); line or change your code like move method in your show method.
For your new error, add this line at top-
use Illuminate\Support\Facades\DB;
When you're going to post/1, you're executing the show method and not move.
Also, change the code to:
<li> Previous</li>
<li> Next</li>
You've said, "and also about the www". I'm pretty sure you're not getting the error about the $previous or $next but you get the error about the www... because you're trying to use text as variable in your code.
Related
I have a DB with multiple tables. I want to display the DB data on my laravel application. I want to display two tables data on the same page. I have created the model, view, and controller for the app but I am being able to display only one table. I cannot show the other table.
I think I need to define a model with multiple relationships which I am not getting how to do.
My tables are called posts and videos I have nothing on my model. the controller and the view is given below.
Controller
namespace App\Http\Controllers;
use App\Post;
use App\Video;
use Illuminate\Http\Request;
class PostsController extends Controller
{
public function index()
{
$posts = Post::all();
return view('landing')->with('posts', $posts);
}
}
View
#extends('layouts.app')
#extends('layouts.navbar')
#section('title')
Landing Page
#endsection
#section('content')
<main class="py-4">
<div class="container">
<div class="row">
<div class="col-md-8">
<h3>Section 1</h3>
#foreach ($posts as $post)
<ul class="list-group">
<li class="list-group-item">
<a href="/posts/{{ $post->id }}">
{{ $post->title }}
{{ $post->brief }}
{{ $post->body }}
{{ $post->cover_image }}
</a>
</li>
</ul>
#endforeach
</div>
<div class="col-md-4">
<h3>Section 2</h3>
#foreach ($videos as $video)
<ul class="list-group">
<li class="list-group-item">
<a href="/videos/{{ $video->id }}">
{{ $video->title }}
</a>
</li>
</ul>
#endforeach
</div>
</div>
</div>
</main>
#endsection
Route on the web.php
<?php
use App\Http\Controllers\PagesController;
use Illuminate\Support\Facades\Route;
Route::get('/', 'PostsController#index');
Route::get('/', 'VideosController#index');
Route::get('/posts/{post}', 'PostsController#show');
Route::resource('posts', 'PostsController');
Route::resource('videos', 'VideosController');
Auth::routes();
Controller for videos data table
<?php
namespace App\Http\Controllers;
use App\Video;
use Illuminate\Http\Request;
class VideosController extends Controller
{
public function index()
{
$videos = Video::all();
return view('landing')->with('videos', $videos);
}
}
On this code I see this problem
If I remove the route for videos on my web.php I could see posts data.
So how could I display both the posts and the videos data at the same time?
Pass both Model together :
<?php
namespace App\Http\Controllers;
use App\Video;
use App\Post;
use Illuminate\Http\Request;
class VideosController extends Controller
{
public function index()
{
$videos = Video::all();
$posts = Post::all();
return view('landing', compact('videos','posts'));
}
}
public function profile($id)
{
$id = Crypt::decrypt($id);
$measurements = DB::select( DB::raw("SELECT * FROM measurements WHERE custom_id = '$id'") );
$customers = DB::table('customers')->where('customer_id', '=', $id)->get();
return view('measurements.profile', compact('measurements','customers'));
}
Looking to solve this error that I'm getting when trying to display some data to the view. I'm working with v5.7 and I have a feeling it might be something with the index method in my controller, I could be very wrong. If there is any more info that is needed please let me know.
Trying to get property 'slug' of non-object (0)
Route:
Route::get('/category/{category}','BlogController#category')->name('category');
BlogCategory Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class BlogCategory extends Model
{
protected $fillable = ['title', 'slug'];
public function posts()
{
return $this->hasMany(Post::class);
}
public function getRouteKeyName()
{
return 'slug';
}
}
Post Model
public function category()
{
return $this->belongsTo(BlogCategory::class);
}
Controller:
protected $limit = 3;
public function index()
{
$categories = BlogCategory::with(['posts' => function ($query) {
$query->published();
}])->orderBy('title', 'asc')->get();
$posts = Post::with('author')
->latestFirst()
->published()
// ->filter(request()->only(['term','year','month']))
->simplePaginate($this->limit);
return view('pages.frontend.blog.index', compact('posts', 'categories'));
}
public function category(BlogCategory $category)
{
$categoryName = $category->title;
$categories = BlogCategory::with(['posts' => function ($query) {
$query->published();
}])->orderBy('title', 'asc')->get();
$posts = $category->posts()
->with('author')
->latestFirst()
->published()
->simplePaginate($this->limit);
return view("pages.frontend.blog.index", compact('posts', 'categories', 'categoryName'));
}
View:
#foreach ($posts as $post)
<article class="post-item">
#if ($post->image_url)
<div class="post-item-image">
<a href="{{ route('blog.show', $post->slug) }}">
<img src="{{ $post->image_url }}" alt="">
</a>
</div>
#endif
<div class="post-item-body">
<div class="padding-10">
<h2>
{{ $post->title }}
</h2>
{!! $post->excerpt_html !!}
</div>
<div class="post-meta padding-10 clearfix">
<div class="pull-left">
<ul class="post-meta-group">
<li>
<i class="fa fa-user"></i>
{{ $post->author->name }}
</li>
<li>
<i class="fa fa-clock-o"></i>
<time> {{ $post->date }}</time>
</li>
<li>
<i class="fa fa-folder"></i>
{{ $post->category->title }}
</li>
<li>
<i class="fa fa-comments"></i>
4 Comments
</li>
</ul>
</div>
<div class="pull-right">
Continue Reading »
</div>
</div>
</div>
</article>
#endforeach
Post table
Blog Cats table
The belongsTo function accepts a second argument for the name of the foreign key in your posts table, if you do not provide it the framework will try to guess what is the foreign key column name giving the name of the function as pattern, in your case category(), so the framework is searching for category_id, however, your foreign key column name is blog_category_id.
public function category()
{
return $this->belongsTo(BlogCategory::class, 'blog_category_id');
}
You should call the category relationship in the index of your controller, if this view is related to the index method!
public function index()
{
$categories = BlogCategory::with(['posts' => function ($query) {
$query->published();
}])->orderBy('title', 'asc')->get();
$posts = Post::with('author')
->category()
->latestFirst()
->published()
// ->filter(request()->only(['term','year','month']))
->simplePaginate($this->limit);
return view('pages.frontend.blog.index', compact('posts', 'categories'));
}
I have tree structure of categories. Now I have to display only that categories which is not applied in a particular business.
Code in Controller
public function edit($id)
{
try
{
$id=Crypt::decrypt($id);
$business=Business::findOrFail($id);
$business_contact_details=BusinessContactDetails::where('business_id',$id)->select('contact_no','id')->get();
$business_working_hours=BusinessWorkingHours::where('business_id',$id)->get();
$business_categories=BusinessCategories::leftJoin('categories','categories.id','=','category_id')->where('business_id',$id)->where('categories.parent_id','0')->select('categories.name as name','approved','category_id','business_categories.id as id')->get();
$categories = Categories::where('parent_id', '=', 0)->get();
return view('admin.businesses.edit',compact('business','business_contact_details','business_working_hours','categories','category_counter','business_categories'));
}
catch(DecryptException $e)
{
return view('errors.404');
}
}
Code in Model
public function subChilds(){
return $this->hasMany('App\Categories','parent_id','id')->whereNotExists(function($query){
$query->from('business_categories')->whereRaw('categories.id=business_categories.category_id')->where('business_id',2);
});
}
Code in edit View
<div class="col-md-6">
<ul id="tree1">
#foreach($categories as $category)
<li>
<input type="checkbox" value="{{$category->id}}" name="categories[]">
{{ $category->name }}
#if(count($category->subChilds($business->id)))
#include('admin.businesses.manageChildSub',['subChilds' => $category->subChilds($business->id)])
#endif
</li>
#endforeach
</ul>
</div>
Code in manageChildSub View
<ul>
#foreach($subChilds as $child)
<li>
<input type="checkbox" value="{{$child->id}}" name="categories[]">
{{ $child->name }}
#if(count($child->childs))
#include('manageChildSub',['subChilds' => $child->subChilds($business->id)])
#endif
</li>
#endforeach
</ul>
Here, You can see that I have passed business_id as 2, but I have to pass it as my current business ID. Basically I need to call the model function with ID.
After changing to this, I am not getting any subcategories.
You can try this:
public function subChilds($business_id){
return $this->hasMany('App\Categories','parent_id','id')
->whereNotExists(function($query) use ($business_id){
$query->from('business_categories')
->whereRaw('categories.id=business_categories.category_id')
->where('business_id', $business_id);
});
}
Okay i'm trying get "likes" and "users" in Posts by relationship hasOne.
here is my Post.php Model
class Posts extends Model
{
protected $table = 'posts';
public function User()
{
return $this->hasOne(User::class, 'id', 'user_id');
}
public function Like()
{
return $this->hasOne(Like::class, 'post_id', 'id');
}}
My Blade template
#foreach ($showdeals as $deal)
<div class="tab-pane active" id="home" role="tabpanel">
<div class="card-body">
<div class="profiletimeline">
{{$deal->like->status}}
<br>
{{$deal->user->email}}
<div class="sl-item">
<div class="sl-left"> <img src=" {{asset( '/assets/images/users/2.jpg')}}" alt="user" class="img-circle"> </div>
<div class="sl-right">
<div> {{$deal->user->username}} || {{$deal->subject}} <Br> <span class="sl-date">{{$deal->created_at}}</span>
<div class="m-t-20 row">
<div class="col-md-3 col-xs-12"><img src="{{$deal->image}}" alt="user" class="img-responsive radius"></div>
<div class="col-md-9 col-xs-12">
<p> {{$deal->body}} </p> עבור למוצר </div>
</div>
<div class="like-comm m-t-20"> 2 תגובות <i class="fa fa-heart text-danger"></i> 5 לייקים </div>
</div>
</div>
</div>
</div>
<hr></div>
</div>
#endforeach
And there is my Controller
class PostsController extends Controller
{
public function showdeals()
{
$showdeals = Posts::with( 'User', 'Like')->get();
return view('posts.show', compact('showdeals'));
}
public function helpnewview(){
return view('posts.anew');
}
public function helpnew(Request $request){
//User pick link
$userlink = $request['userlink'];
return \Redirect::route('newdeal', compact('userlink'));
}
public function new(Request $request)
{
//Emdeb user link
$link = Embed::create($request['userlink']);
$linke = $request['userlink'];
return view('posts.new', compact('link', 'userlink', 'linke'));
}
public function create(Request $request)
{
$posts = New Posts;
$posts->user_id = Auth::User()->id;
$posts->subject = $request['subject'];
$posts->body = $request['body'];
$posts->link = $request['link'];
$posts->price = $request['price'];
$posts->image = $request['image'];
$posts->tag = $request['tag'];
$posts->save();
return back();
}
}
Now if I do something like {{$deal->user->email}} its will work,
if I go to something like this {{$deal->like->status}} its does not work,
am I missing something ?
If you want multiple relationships to be eagerly loaded you need to use an array of relationships: Model::with(['rl1', 'rl2'])->get();
public function showdeals()
{
...
$showdeals = Posts::with(['User', 'Like'])->get();
...
}
EDIT:
From that json in the comments that I see, there is no attribute named status in your Like model so thats probably the root of the problem
Controller edit this code
public function showdeals()
{
$showdeals = Posts::all();
return view('posts.show', compact('showdeals'));
}
And blade file code
#foreach ($showdeals as $deal)
<div class="tab-pane active" id="home" role="tabpanel">
<div class="card-body">
<div class="profiletimeline">
{{ $deal->Like->status }}
<br>
{{ $deal->User->email }}
#endforeach
I think everything is good except
{{$deal->like->status}} {{$deal->user->email}}
Please try as
{{$deal->Like()->status}}
<br>
{{$deal->User()->email}}
My model code
how we can call this function in blade.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BasicModel extends Model
{
public static function get_product_count($id){
$query = "select COUNT(sub_id) AS count FROM products WHERE products.sub_id = $id";
print_r($query);
return $query->row_array();
}
}
My view.blade.php code
count in foreach loop or show in all category
#foreach ($r as $row)
<li class="grid-item type-rent">
<div class="property-block">
<img src="{{ URL::to('/template/images/background-images/sub-category-images/' .$row->sub_cat_images. '')}}" alt=""> <!-- <span class="images-count"><i class="fa fa-picture-o"></i> 2</span> <span class="badges">Rent</span> -->
<div class="property-info">
<h4>{{ ucwords(substr($row->sub_cat_name, 0, 22)) }}</h4>
<span class="location">NYC</span>
<div class="price"><strong>Items</strong><span>
<!-- start count code from here -->
$data = $this->BasicModel->count {{ ($row->sub_id) }}
echo $data['count'];
</span></div>
</div>
<!-- <div class="property-amenities clearfix"> <span class="area"><strong>5000</strong>Area</span> <span class="baths"><strong>3</strong>Baths</span> <span class="beds"><strong>3</strong>Beds</span> <span class="parking"><strong>1</strong>Parking</span> </div> -->
</div>
</li>
#endforeach
My BasicController Code
public function grid(Request $request, $id)
{
if ($id == 1) {
$r = DB::table('sub_category')->select('*')->where('cat_id', $id)
->where('sub_status', '1')->orderBy('sub_id', 'asc')->get();
$name = DB::table('category')->where('cat_id', $id)->get();
return view('buy-and-sell/grid', compact('r','name','count'));
}
image for your help
image for your help
problem in this image please solve the problem
Although its no good Practice Accessing the DB in Blade (better do this in the controller and pass the data) you can do:
<div class="price"><strong>Products</strong>
<span>
{{ BasicModel::where('sub_id', $row->sub_id)->count() }}
</span>
</div>
Its not tested, but have a look at the Eloquent docs, the count() method is explained there.
Update: I am not shure if laravel will find the class BasicModel (I never would access Models directly in blade, as stated do this in the controller and pass the data.) So maybe you need to write it with the full Namespace most likely {{ \App\BasicModel::where() }}.