Two tables join data passing to view in laravel - php

need to get data from status table in view. Tried to put alias, googled over 3 hours, I'm lost. Any ideas how?
Controler code:
$action= DB::table('actionplan')
->join('status','actionplan.status','=','status.id')
->select('status.name as testas','actionplan.*')
->where([['user_id','=',$name],['done','<>',1]])->get();
View code:
#foreach($teams as $item)
<th scope="row">1</th>
<td>{{$item->name}}</td>
<td>{{$item->start_date}}</td>
<td>{{$item->end_date}}</td>
<td>{{$item->comment}}</td>
<td>{{$item->status()->name}}</td>

You should really implement models for your database tables. While this isn't the advice you're asking for, it will greatly simplify your queries in this regard.
Your ActionPlan.php model:
use Illuminate\Database\Eloquent;
class ActionPlan extends Model
{
protected $table = 'actionplan';
public function status()
{
return $this->hasOne(App\Status::class, 'id', 'status');
}
}
Your Status.php model:
use Illuminate\Database\Eloquent;
class Status extends Eloquent
{
protected $table = 'status';
}
Your query:
$actions = Action::whereHas('status')
->where('user_id', '=', $name)
->where('done', '<>', 1)
->get();
Or:
$actions = Action::whereHas('status')
->whereUserId($name)
->having('done', '<>', 1)
->get();

Related

Laravel Eloquent Model with relationship

I have implemented eloquent relationship in my code but Laravel unable to read the function that I created to map the eloquent relationship in the model.
User Model
public function products(){
return $this->hasMany(Product::class,'userid');
}
Product Model
public function users(){
return $this->belongsTo(User::class);
}
Product Controller
$products = Product::with('Users')->Users()->where('users.isActive',1)->get();
return view('product',compact('products'));
I keep getting error from the product controller, I also attached the error that I current encountered as below.
How can I get all the product and user data with the where condition such as "Users.isActive = 1".
Thanks.
You can use whereHas to filter from a relationship.
$products = Product::with('users')
->whereHas('users', function ($query) {
$query->where('isActive', 1);
})
->get();
Also it is generally a good idea to use singular noun for belongsTo relationship because it returns an object, not a collection.
public function user() {
return $this->belongsTo(User::class);
}
$products = Product::with('user')
->whereHas('user', function ($query) {
$query->where('isActive', 1);
})
->get();
EDIT
If you want to retrieve users with products you should query with User model.
$users = User::with('products')
->where('isActive', 1)
->get();
Then you can retrieve both users and products by
foreach($users as $user) {
$user->products;
// or
foreach($users->products as $product) {
$product;
}
}
You can use whereHas() method for this purpose. Here is the doc
$products = Product::with('users')->whereHas('users', function (Illuminate\Database\Eloquent\Builder $query) {
$query->where('isActive', 1);
})->get();
$users = $products->pluck('users');
return view('product',compact('products'));
You have a typo after the with, is users instead of Users and you're redundant about the Query Builder, remove the ->Users():
Before:
$products = Product::with('Users')->Users()->where('users.isActive',1)->get();
return view('product',compact('products'));
After:
$products = Product::with('users')->where('users.isActive',1)->get();
return view('product',compact('products'));
Fix that and all should work.

Laravel 5: Eloquent whereHas subquery doesn't filter results

I'm trying to retrieve some results from a model using a relation and I'm trying to apply some filters on that relationship.
Here is the model:
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UserProduct extends Model
{
protected $primaryKey = null;
public $incrementing = false;
protected $table = "user_product";
public $fillable = [
...
"product_id",
"user_id",
"is_featured",
"is_hidden_from_latest"
...
];
public function product()
{
return $this->belongsTo("\\App\\Models\\Product", "product_id", "id");
}
...
}
and here is the related model:
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $table = "products";
public $timestamps = false;
public $fillable = [
...
];
public function userProduct()
{
return $this->hasOne("\\App\\Models\\UserProduct", "product_id", "id");
}
...
}
Here is the query on UserProduct model and product relationship:
$user_products = UserProduct::with("product")
->whereHas("product", function($q) {
$q->where("product_status", "live")
->where("parent_child", "Child");
})->where("is_featured", 1)
->orWhere("is_hidden_from_latest", 0)
->orderBy("is_featured", "desc")
->orderBy("updated_at")
->get();
The problem is that whereHas subquery doesn't seem to filter anything no matter what value to compare to I use for each product_status and parent_child.
Is there something that I don't do correctly?
Update: Seems that the game breakers are these two where() statements at the end:
....
->where("is_featured", 1)
->orWhere("is_hidden_from_latest", 0)
....
and more specifically the orWhere() statement.
Try this way
$user_products = UserProduct::with("product")
->whereHas("product", function($q) {
$q->where("product_status", "live")
->where("parent_child", "Child");
})
->where(function ($query) {
$query->where("is_featured", 1)
->orWhere("is_hidden_from_latest", 0);
})
->orderBy("is_featured")
->orderBy("updated_at")
->get();
I just removed where("is_featured", 1) and replaced it with just where("is_hidden_from_latest", 0) as I order the results ascendantly by is_featured anyway.
The whereHas() subquery works properly. :)

Count how many reviews a post has - Laravel 5.2

I need to count how many reviews a post has. How would I go about doing that?
Here is my Listing.php Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Listing extends Model
{
public function reviews()
{
return $this->hasMany('\App\Review');
}
}
Here is my Review.php model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Review extends Model
{
protected $fillable = ['stars','name','comment'];
public function listing()
{
return $this->belongsTo('\App\Listing');
}
}
Here is my method that I'am trying to count in controller
public function mostReviews(Request $request) {
$listings = Review::orderBy('-- most reviews here --')->take(10)->get();
$headline = 'Most Reviewed Listings';
return view('pages.listings', compact('listings', 'headline'));
}
Here is my review table:
I haven't tested it but the query below (using the query builder) should give you what you want - 10 listings with the most reviews. Additionally average_stars column should return average stars rate. You can easily modify the query to get 10 highest rated listings by changing orderBy to average_stars.
$listings = \DB::table('reviews AS r')
->select([
'r.listing_id',
\DB::raw('COUNT(*) AS no_of_reviews'),
\DB::raw('AVG(r.stars) AS average_stars'),
'l.*'])
->join('listings AS l', 'l.id', '=', 'r.listing_id')
->limit(10)
->orderBy('no_of_reviews', 'DESC')
->groupBy('listing_id')
->get();
Please note version up to version 5.2 of Laravel this will return array of stdObject. You can easily access those in your blade template in a similar way as Eloquent Collection.
#foreach($listings as $listing)
<tr>
<td>{{ $listing->id }}</td>
<td>{{ $listing->title }}</td>
<td>{{ $listing->no_of_reviews }}</td>
<td>{{ floor($listing->average_stars) }}</td>
</tr>
#endforeach
This is what I did:
public function mostReviews() {
$reviews = DB::table('reviews')
->select(DB::raw('AVG(stars) as review_score, listing_id'))
->groupBy('listing_id')
->orderBy('review_score', 'desc')
->limit(10)
->get();
foreach($reviews as $key => $review) {
$reviews[$key] = Listing::find($review->listing_id);
}
return view('listings.most-reviews', [
'listings' => $reviews
]);
}
Try this
$review = Review::orderBy('-- most reviews here --');
$reviewCount = $review->count();
$listings=$review->take(10)->get();
The following should work
$listing = Listing::with('reviews')->orderByRaw(function($listing)
{
return $listing->review->count();
}, desc)->take(10)->get();
in your listing model:
public function countReview() {
return count($this->reviews);
}
in your views :
{{$listing->countReview()}}
maybe in controller you can write somthing like :
public function mostReviews() {
Review::orderBy('listing', 'desc')->blahblah; // or 'asc'
}

Laravel get roles color and more

I'm trying to make a RBAC in my own forum software.
For so far, the permissions work, but the problem is, when I want to add colors to usernames (what MyBB also has) something doesn't work and I don't understand it propperly.
So I have an ForumController with this code inside:
<?php
class ForumController extends \BaseController {
public function index()
{
$forums = Forums::orderBy('disp_order', 'asc')->get();
$categories = Categorie::orderBy('disp_order', 'asc')->get();
return View::make('index')->with('forums', $forums)->with('categories', $categories);
}
public function forum($name)
{
$forums = Forums::where('name', '=', str_replace('Forum-', '',str_replace('-', ' ', $name)))->first();
$categories = Categorie::orderBy('disp_order', 'asc')->get();
return View::make('forum')->with('forums', $forums)->with('categories', $categories);
}
public function categorie($name)
{
$categories = Categorie::where('name', '=', str_replace('Categorie-', '',str_replace('-', ' ', $name)))->first();
$threads = Thread::orderBy('date_posted', 'asc')->get();
return View::make('categorie')->with('categories', $categories)->with('threads', $threads);
}
public function thread($title)
{
$thread = Thread::where('title', '=', str_replace('Thread-', '',str_replace('-', ' ', $title)))->first();
$comments = Comment::orderBy('posted_at', 'asc')->get();
return View::make('thread')->with('threads', $thread)->with('comments', $comments);
}
}
Good, everything of that works.
But now I need to get the roles for users inside of the function thread.
I also have these models:
There is only an extend to Eloquent and the protected $table inside of these files.
The scheme of my role table looks like this:
I did hear somethig about belongsTo and hasMany, but I really don't understand it...
I want to be able to get the right color on the right user.
So the scheme of the user table:
I hope someone can help me out, because I'm looking for the answer a long time.
I'm using Laravel4
Kindest regards,
Robin
You're right, you need to add some relationships:
// In Comment.php, assuming that your comments table has a user_id field.
public function user()
{
return $this->belongsTo(User::class);
}
// In User.php
public function role()
{
return $this->belongsTo(Role::class);
}
Then adjust your controller to eager load these relationships.
$comments = Comment::orderBy('posted_at')->with('user.role')->get();
Now you can show the color next to a comment in your blade template like:
#foreach ($comments as $comment)
<p>Color: {{ $comment->user->role->colour }}</p>
#endfoeach

Laravel 4 model controller view

how can i use this in the model
now example 1 this work just fine... on the controller
$songs = DB::table('songlist')
->join('historylist', 'songlist.id', '=', 'historylist.songID')
->select('songlist.*', 'historylist.*')
->orderBy('historylist.date_played', 'DESC')
->first();
return View::make('currentsong')
->with('songs', $songs);
but i want to get that from the model my model is
class Radio extends Eloquent
{
public static $timestamps = true;
}
i want my model to look like
class Radio extends Eloquent
{
public static function getSonginfo()
{
$songs = DB::table('songlist')
->join('historylist', 'songlist.id', '=', 'historylist.songID')
->select('songlist.*', 'historylist.*')
->orderBy('historylist.date_played', 'DESC')
->first();
}
}
now how can i pass this model into my controller and view and call the varible as i do right now $songs->title on my view
the part i dont really get is how can i call the model function on the controller and parse it into the view something like this maybe
$songs = Radio::getSonginfo();
return View::make('currentsong')->with('songs', $songs);
now when i call this on my view {{ $songs->title}} i get undefined variable $songs.
any help Thanks.
sorry for my rusty english.
you need to return the variable in your model.
public static function getSonginfo()
{
$songs = DB::table('songlist')
->join('historylist', 'songlist.id', '=', 'historylist.songID')
->select('songlist.*', 'historylist.*')
->orderBy('historylist.date_played', 'DESC')
->first();
return $songs;
}

Categories