Laravel 5.3 How to use multiple controllers in one view - laravel

I'm working with a view that at first displays all products, and on the sidebar, users can see a list of categories. My aim is when users press on any categories, it will display products of that category only. However, since there are 2 controllers is interacting with this view and send the same data, one is not running(CategoriesController). It does not show any error, just when I click on the link of each of the categories, it does not reload the page.
Here is my ProductsController:
class ProductsController extends Controller
{
// display all products and categories
public function index() {
$products = Product::all();
$categories = Category::all();
return view('frontend.product', compact('products','categories'));
}
And my CategoriesController:
class CategoriesController extends Controller
{
public function showProducts($category_id) {
$products = Category::find($category_id)->products;
return view('frontend.product', compact('products'));
}
Here is my view:
// Products part
#foreach($products as $product)
{{ $product->name }}
#endforeach
//Categories part
#foreach($categories as $category)
{{ $category->name }}
#endforeach
And route:
Route::get('/products', [ 'as' => 'products', 'uses' => 'frontend\ProductsController#index']);
Route::get('/categories/{category_id}', ['as' => 'categories', 'uses' => 'backend\CategoriesController#showProducts']);

Just include all of the categories in your showProducts function, and omit the current category:
public function showProducts($category_id)
{
$categories = Category::whereNotIn('id', $category_id)->get();
$products = Category::find($category_id)->products;
return view('frontend.product', compact('products', 'categories'));
}
Now there will be no discrepancies between the variables that are being used.

If I have not misunderstood, I thought you can use #inject in blade. For example:
namespace App\Presenters;
use App\User;
class UserPresenter
{
/**
* 是否顯示email
* #param User $user
* #return string
*/
public function showEmail(User $user)
{
if ($user->show_email == 'Y')
return '<h2>' . $user->email . '</h2>';
else
return '';
}
}
and
<div>
#inject('userPresenter', 'MyBlog\Presenters\UserPresenter')
#foreach($users as $user)
<div>
{!! $userPresenter->showEmail($user) !!}
</div>
</div>

Related

show the data in dropdown fetched from database using laravel 8

i have to show the category values in dropdown in product form,the given code is from my view,the error is undefined $categories.this is my first code in laravel i dont know how to make changings in other files.which variable is used in foreach?or i have to create new function in ProductController?
<form action="/upload_product" method="post">
#csrf
<label>Choose Categories</label>
<select name="category_id" id="category" class="category">
<option disable selected>--select category--</option>
#foreach($categories as $item)
<option value="{{ $item->id }}">{{ $item->name}}</option>
#endforeach
</select>
<input type="text" name="name" placeholder="name">
<input type="number" name="sale_price" placeholder="sale_price">
</form>
Model Product.php
class Product extends Model
{
use HasFactory;
protected $table = 'products';
public $timestamps = true;
public function category(){
return $this->belongsTo('App\Models\Category');
}
}
Model Category.php
class Category extends Model
{
use HasFactory;
public $fillable = [ 'name' ];
protected $dates = [ 'deleted_at' ];
public $timestamps = true;
public function products (){
return $this->hasMany('App\Models\Product');
}
}
ProductController.php
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use App\Models\Category;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function index()
{
$products = Product::all();
return view('products/index', ['products'=>$products]);
}
public function view()
{
$products = Product::with('category')->get();
$categories = Category::with('products')->get();
return view ('product.view')-> with([
'products' => $products,
'categories' => $categories,
]);
}
You have to use like below
public function index(){
$products = Product::all();
$categories = Category::with('products')->get();
return view('products.index', compact('products','categories'));
}
You don't have $categories in your index file.
Based on the index method, you're sendig just products:
public function index()
{
$products = Product::all();
return view('products/index', ['products'=>$products]);
}
So add categories too.
public function index()
{
$products = Product::get();
return view('products/index', ['products'=>$products]);
}
you can do this in three ways
public function index(){
$products = Product::all();
$categories = Category::with('products')->get();
return view('products.index', compact('products','categories'));
}
public function index(){
$products = Product::all();
$categories = Category::with('products')->get();
return view('products.index')->with(['products'=>$products,'categories'=>$categories]));
}
public function index(){
$data['products'] = Product::all();
$data['categories'] = Category::with('products')->get();
return view('products.index',$data);
}

How to show the comments which belongs to the post?

I'm creating a news feed kind of thing where users can post anything and the post will have comments also. I'm able to create the newsfeed and the comment section, but my real problem is I'm not able to show the comments which belongs to the post. Right now all the comments are displayed under every news feed. Though I've declared the eloquent relationship between feed and comment but still I'm not able to save the feed_id in comment table.
This is my FeedsController:-
<?php namespace App\Http\Controllers;
use Request;
use Auth;
use Sentinel;
use App\Feed;
use App\Http\Requests;
use App\Blog;
use App\Http\Controllers\Controller;
use App\Comment;
class FeedsController extends Controller
{
public function index() {
$comments = Comment::latest()->get();
$feeds = Feed::where('user_id', Sentinel::getUser()->id)->latest()->get();
$blogs = Blog::latest()->simplePaginate(5);
$blogs->setPath('blog');
return view('action.index')->with('feeds', $feeds)->with('comments', $comments)->with('blogs', $blogs);
}
public function store(Requests\CreateFeedRequest $request){
$requet = $request->all();
$request['user_id'] = Sentinel::getuser()->id;
Feed::create($request->all());
return redirect('home');
}
public function storecomment(Requests\CommentRequest $request, Feed $feed)
{
$comment = new Comment;
$comment->user_id =Sentinel::getuser()->id;
$comment->feed_id = $request->feed_id;
$comment->comment = $request->comment;
$comment->save();
return redirect('home');
}
}
This is the models:
Comment model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $fillable = [
'comment',
'user_id',
'feed_id'
];
public function feed()
{
return $this->belongsTo('App\Feed');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
Feed model:
use Illuminate\Database\Eloquent\Model;
class Feed extends Model
{
protected $fillable = [
'feed_id',
'user_id',
'feed_content'
];
public function user()
{
return $this->belongsTo('App\User');
}
public function comment()
{
return $this->hasMany('App\Comment');
}
}
User model:-
<?php namespace App;
use Cartalyst\Sentinel\Users\EloquentUser;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends EloquentUser {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes to be fillable from the model.
*
* A dirty hack to allow fields to be fillable by calling empty fillable array
*
* #var array
*/
protected $fillable = [];
protected $guarded = ['id'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* To allow soft deletes
*/
use SoftDeletes;
protected $dates = ['deleted_at'];
public function feeds()
{
return $this->hasMany('App\Feed');
}
public function comment()
{
return $this->hasMany('App\Comment');
}
}
This is my feed.blade.php where I'm displaying the feeds output and commnets
#foreach($feeds as $feed)
<article class="media">
<div class="well">
<div class="pull-left">
<img class="profile" src="{{ URL::to('/uploads/users/'.$feed->user->pic) }}" class="img-responsive" alt="Image" style="width:48px;height:48px;padding-right : 10px;padding-bottom: 5px;">
</div>
<strong>{{ $feed->user->first_name }}
{{ $feed->user->last_name }}
<small> posted </small>
</strong>
{{ $feed->created_at->diffForHumans() }}<br><hr>
{{ $feed->feed_content }}
<hr>
{!! Form::open(['url' => 'home/{storecomment}']) !!}
<div class="form-group">
{!! Form::text('comment', null, ['class'=>'form-control', 'rows'=>3, 'placeholder'=>"Comment"]) !!}
</div>
<div class="form-group feed_post_submit">
{!! Form::submit('Comment', ['class' => 'btn btn-default btn-xs']) !!}
</div>
{!! Form::close() !!}
#foreach($comments as $comment)
<div class="pull-left">
<img class="profile" src="{{ URL::to('/uploads/users/'. $comment->user->pic) }}" class="img-responsive" alt="Image" style="width:48px;height:48px;padding-right : 10px;padding-bottom: 5px;">
</div>
{{ $comment->user->first_name }}
{{ $comment->created_at->diffForHumans() }}
{{ $comment->comment }}<hr>
#endforeach
</div>
</article>
#endforeach
Can anyone tell me how to store the feed_id into comment table and displaying the comments according to the feed. Thank You. I'm using Laravel 5.1
Based on our lengthy convo -
To save the feed_id (which is our foreign key for future relationships), you need to set/send the feed_id in your POST request. Laravel is not magic and won't know this automatically. You can do this by adding a hidden input, like so:
<input type="hidden" name="feed_id" value="{{ $feed->feed_id }}" />
In your FeedController, change your index to this:
public function index() {
// $comments = Comment::latest()->get(); remove this
// notice the "with" below. I'm eager loading in relations here
$feeds = Feed::with('comments', 'user')->where('user_id', Sentinel::getUser()->id)->latest()->get();
$blogs = Blog::latest()->simplePaginate(5);
$blogs->setPath('blog');
return view('action.index', compact('feeds', 'blogs'));
}
Feed Model should have the correct relationships, as below:
class Feed extends Model
{
protected $fillable = [
'feed_id',
'user_id',
'feed_content'
];
public function user()
{
return $this->belongsTo('App\User', 'id', 'user_id');
}
public function comments()
{
return $this->hasMany('App\Comment', 'feed_id', 'feed_id');
}
}
Comment Model should have the correct relationships, as below:
class Comment extends Model
{
protected $fillable = [
'comment',
'user_id',
'feed_id'
];
public function feed()
{
return $this->belongsTo('App\Feed');
}
public function user()
{
return $this->hasOne('App\User', 'id', 'user_id');
}
}
Now you should be able to run your foreach as you currently have it.

Get data from another model laravel-api-generator

I am using https://github.com/mitulgolakiya/laravel-api-generator
I would like to get data from another model. When inserting a post pick the category data.
PostController.php
class PostController extends AppBaseController
{
/** #var PostRepository */
private $postRepository;
/** #var CategoriesRepository */
private $categoriesRepository;
function __construct(PostRepository $postRepo, CategoriesRepository $categoriesRepo)
{
$this->postRepository = $postRepo;
$this->categoriesRepository = $categoriesRepo;
}
/**
* Display a listing of the Post.
*
* #return Response
*/
public function index()
{
$posts = $this->postRepository->paginate(10);
$categories = $this->categoriesRepository->all('id', 'desc')->get();
return view('posts.index')
->with('posts', $posts)
->with('categories', $categories);
}
fields.blade.php
{!! Form::select('category_id', Categories::lists('name', 'id'), ['class' => 'form-control']) !!}
How can I do this? Thank you!
You should make the list in controller and pass it to the view.
public function index()
{
$posts = $this->postRepository->paginate(10);
$categories = $this->categoriesRepository->all('id', 'desc')->get();
$categoryList = [ '' => '--select--' ] + $categories->lists('name', 'id');
return view('posts.index')
->with('posts', $posts)
->with('categories', $categories)
->with('categoryList', $categoryList);
}
And use this variable to generate the select.
{!! Form::select('category_id', $categoryList, ['class' => 'form-control']) !!}
I think you should use ViewComposers and pass category list array in fields.blade.php. so it will not affect directly your templates or generator.
Whenever you have a requirement where you always have to pass fields of another model in any view, I think you should use view composer.

Laravel 4 - get images of item in blade view

I'm new in Laravel and stuck with a noob problem. I have 3 tables, users, items, item_images. When i post a item i save the images to item_images with the item_id and the other input data to the items table. now, how to get the first of x images for the item in my foreach loop?
This is my view
#foreach ($items as $item)
<div class="item">
<div class="item-image">
<img src="/uploads/{{ $item->image }}"/>
</div>
{{ $item->title }}
{{ $item->type }}
{{ $item->label }}
</div>
#endforeach
This is the ItemImages Controller
<? class ItemImages extends Eloquent {
protected $fillable = array(
'item_id',
'image'
);
protected $table = 'item_images';
public function item() {
return $this->belongsTo('Item');
}
}
The Item Controller
<? class Item extends Eloquent {
protected $fillable = array(
'user_id',
'type',
'title',
'label'
);
protected $table = 'items';
public function item() {
return $this->hasMany('ItemImages');
}
}
And the home controller
<?php class HomeController extends BaseController {
public function home() {
$items = Item::all();
$images = ItemImages::all();
$users = User::orderByRaw("RAND()")->take(2)->get();
return View::make('home', array(
'items' => $items,
'users' => $users,
'images' => $images
));
}
}
thanks in advance.
Looks like you have not defined relationships. I believe doing that will make the answer much simpler than the following:
<img src="/uploads/{{
$images->filter(function($image) use( $item ) {
return $image->item_id == $item->id;
})->values()->image
}}"/>

Laravel 4 login validation issue

I'm having trouble logging in. Even when there are no validation errors to be found, it goes to the else statement block in my postIndex method and brings me back to the login page. Any idea on what the problem is and what do i need to change to fix it?
routes.php
<?php
Route::get('/', 'HomeController#getGuestIndex');
Route::controller('login', 'LoginController');
?>
HomeController.php
<?php
class HomeController extends BaseController {
public function getGuestIndex()
{
return View::make('guests.index');
}
public function getAdminIndex()
{
return View::make('admin.index');
}
}
?>
LoginController.php
<?php
class LoginController extends BaseController {
public function getIndex()
{
// Check if we are already logged in.
if (Auth::check()) {
return Redirect::action('HomeController#getAdminIndex')
->with('message', 'You are already logged in');
}
return View::make('guests.login')
->with('title', 'Login');
}
public function postIndex()
{
// Get all the inputs
$user = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
$validation = User::validate($user);
if ($validation->passes()) {
// Try to log the user in.
if (Auth::attempt($user)) {
return Redirect::action('HomeController#getAdminIndex')
->with('message', 'You have logged in successfully');
}
return Redirect::to('login')
->withErrors($validation)
->withInput(Input::except('password'));
} else {
// Something went wrong.
return Redirect::back()
->withErrors($validation)
->withInput(Input::except('password'));
}
}
}
?>
BaseModel.php
<?php
class BaseModel extends Eloquent {
public static function validate($inputs)
{
return Validator::make($inputs, static::$rules);
}
}
?>
User.php
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends BaseModel implements UserInterface, RemindableInterface {
protected $table = 'users';
protected $hidden = array('password');
protected static $rules = array(
'username' => 'required|alpha_dash|min:4',
'email' => 'required|email',
'password' => 'required|alpha_num|min:8|confirmed',
'password_confirmation' => 'required|alpha_num|min:8'
);
public function getAuthIdentifier()
{
return $this->getKey();
}
public function getAuthPassword()
{
return $this->password;
}
public function getReminderEmail()
{
return $this->email;
}
}
?>
login.blade.php
#extends('layouts.master')
#section('content')
<h2>Login into your account</h2>
{{ Form::open(array('url' => 'login')) }}
<p>
{{ Form::label('username', 'Username') }}
{{ Form::text('username', Input::old('username')) }}
</p>
<p>
{{ Form::label('password', 'Password') }}
{{ Form::password('password') }}
</p>
<p>
{{ Form::submit('Login') }}
</p>
{{ Form::close() }}
<p>{{ $errors->first('username') }}</p>
<p>{{ $errors->first('password') }}</p>
#stop
Based on your question and example script the validation is failing.
The problem is likely with the model based validation implementation. You are validating login with registration rules.
One set of validation rules does not fit all situations.
If you add the following lines to your login.blade.php I think you will see additional errors:
<p>{{ $errors->first('email') }}</p>
<p>{{ $errors->first('password_confirmation') }}</p>
To fix it, you will need to either change the validation rules on your model, or change the validation implementation. These two excellent tutorials show a couple approaches:
https://tutsplus.com/lesson/validation-services/
https://tutsplus.com/lesson/validating-with-models-and-event-listeners/

Resources