This is my code:
The Model:
public static function myWishlist(){
$id = Auth::id();
$book_id = Wishlist::where('user_id', $id)->pluck('book_id');
return DB::table('books')->whereIn('id', $book_id)->get();
The Controller:
public function index(Request $request)
{$books = Wishlist::myWishlist()->paginate(20);
return view('wishlistCRUD.index', compact('books'))
->with('i', ($request->input('page', 1) - 1) * 5);
But instead of showing me all of the specified books, it says:
Method paginate does not exist.
I also tried this in the Model:
$book_id = Wishlist::where('user_id', $id)->pluck('book_id');
return Book::whereIn('id',$book_id)->get();
But then it returns a collection and I dont know how to show that in my view.
You can not use paginate after getting result.
You can do it in this way:
public static function myWishlist() {
$id = Auth::id();
$book_id = Wishlist::where('user_id', $id)->pluck('book_id');
return Book::whereIn('id', $book_id);
}
public function index(Request $request) {
$books = Wishlist::myWishlist()->paginate(20);
return view('wishlistCRUD.index', compact('books'))
->with('i', ($request->input('page', 1) - 1) * 5);
}
First there is no need to use a static function eloquent already does that.
And second you could use local scopes like this:
Model:
public function scopeUserWishlist($query, $userID)
{
// Although a join would be nicer !
$book_ids = Wishlist::where('user_id', $userID)
->pluck('book_id');
return $query->whereIn('id', $book_ids);
}
Controller:
public function index(Request $request)
{
$books = Wishlist::userWishlist(Auth::id())
->paginate(20);
return view('wishlistCRUD.index')
->with('books', $books)
->with('i', ($request->input('page', 1) - 1) * 5);
}
Related
I have a project in Laravel 7 that has a column in the user table called organ_id that has different numbers for different users (1,2,...)
Now I want to use organ_id inside my controller, which is as follows, and by using if, different information is given to each user according to the organ number.
ProductsController.php
namespace App\Http\Controllers;
use App\User;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
if (Auth::check())
{
$organ_id = Auth::user()->getId();
}
class ProductsController extends Controller
{
public function test(Request $request) {
if ($organ_id == 1) {
function orders(Request $request) {
$data = DB::table('products_1')
->orderBy('id', 'asc')
->paginate(14);
return view('products', compact('data'));
}
function posts(Request $request) {
$data = DB::table('posts')
->orderBy('id', 'asc')
->paginate(25);
return view('posts', compact('data'));
}
/*
other functions
.
.
.
*/
}
if ($organ_id == 2) {
function orders(Request $request) {
$data = DB::table('products_2')
->orderBy('id', 'asc')
->paginate(14);
return view('products', compact('data'));
}
function posts(Request $request) {
$data = DB::table('posts')
->orderBy('writer_id', 'asc')
->paginate(10);
return view('posts', compact('data'));
}
/*
other functions
.
.
.
*/
}
}
}
User.php
public function getId()
{
return $this->organ_id;
}
Since it is not possible to use if in the controller, I wrote the public function test() and put if inside this function.
Unfortunately, in this case, the browser can not find the orders function.
you can do that
$organ_id = User::where('id',auth()->user()->id)->pluck('organ_id')->first();
if ($organ_id == 1) {
//code
}
i am using laravel 7 eloquent. i am very new to laravel
this is basic method i am getting data from category table
public function category(){
$category = Category::orderBy('id', 'desc')->get();
$data['pageData'] = $category;
$data['pageTitle'] = "Category";
return view('admin.category.index')->with('data',$data);
}
But i want to do something like this
public function category(){
$category = Category::orderBy('id', 'desc')->get();
if(!empty($_REQUEST['parent_id']))
$category->where('parent_id',$_REQUEST['parent_id']);
$data['pageData'] = $category;
$data['pageTitle'] = "Category";
return view('admin.category.index')->with('data',$data);
}
So how can this is possible using eloquent.
Any help out of this question are helpful for me as i am beginner.
Try this
public function category(){
$query = Category::orderBy('id','desc');
$query = where('parent_id',$_REQUEST['parent_id']);
$category = $query->get();
$data['pageData'] = $category;
$data['pageTitle'] = 'Category';
return view('admin.category.index')->with('data',$data);
}
You can leverage the when() eloquent method to add conditional clause to query:
public function category()
{
$category = Category::when(request('parent_id'),function($parent_id,$query)
{
$query->where('parent_id',$parent_id);
})->orderBy('id', 'desc')->get();
$data['pageData'] = $category;
$data['pageTitle'] = "Category";
return view('admin.category.index')->with('data',$data);
}
when() doc reference https://laravel.com/docs/8.x/queries#conditional-clauses
You can use the when method to only apply the query if the request contains the parent_id.
From the docs:
Sometimes you may want certain query clauses to apply to a query based
on another condition. For instance, you may only want to apply a where
statement if a given input value is present on the incoming HTTP
request. You may accomplish this using the when method:
$role = $request->input('role');
$users = DB::table('users')
->when($role, function ($query, $role) {
return $query->where('role_id', $role);
})
->get();
The when method only executes the given closure when the first
argument is true. If the first argument is false, the closure will not
be executed. So, in the example above, the closure given to the when
method will only be invoked if the role field is present on the
incoming request and evaluates to true.
In your case it would be the following:
use Illuminate\Http\Request;
public function category(Request $request)
{
$categories = Category::query()
->when($request->input('parent_id'), function ($query, $parent_id) {
$query->where('parent_id', $parent_id);
})
->orderBy('id', 'desc')
->get();
$data['pageData'] = $categories;
$data['pageTitle'] = "Category";
return view('admin.category.index')->with('data', $data);
}
You can do as like below
public function category(){
$category = new Category();
if(!empty($_REQUEST['parent_id'])){
$category->where('parent_id',$_REQUEST['parent_id']);
}
$category = $category->orderBy('id', 'desc')->get()
$data['pageData'] = $category;
$data['pageTitle'] = "Category";
return view('admin.category.index')->with('data',$data);
}
Try using laravel when condition
https://laravel.com/docs/8.x/queries#conditional-clauses
Improve your question with proper details. as you mention in the question the second coding path won't work because it doesn't have $request query to functionally run the if statement. anyhow if you want to get only pageData & pageTitle in laravel Eloquent ORM you have to select both columns as follows.
class CategoryController extends Controller
{
public function category(){
$category = Category::select('pageData', 'pageTitle')->orderBy('id', 'desc')->get();
return view('admin.category.index')->with('data', $category);
}
}
For example I can use:
$address = $user->address
which will return the addresses for the user.
// User.php (model)
public function address()
{
return $this->hasMany(Address::class, 'refer_id', 'id');
}
public function billingAddress()
{
return $this->address()
->where('type', '=', 1)
->where('refer_id', '=', $this->id)
->first();
}
However, I would like to return the BillingAddress for the user depending on this where clause. How do I do it?
EDIT:
If I use this inside... OrderController#index it returns correctly
$orders = Order::with('order_fulfillment', 'cart.product', 'user.address', 'payment')->get();
return new OrderResource($orders);
However, If I change it to:
$orders = Order::with('order_fulfillment', 'cart.product', 'user.billingAddress', 'payment')->get();
return new OrderResource($orders);
I get this error:
Symfony\Component\Debug\Exception\FatalThrowableError
Call to a member function addEagerConstraints() on null
One option is you can use whereHas in your query. For example,
$orders = Order::with('order_fulfillment', 'cart.product', 'user.address', 'payment')
->whereHas(
'address', function ($query) {
$query->where('type', '=', 1)
->first();
}
)->get();
return new OrderResource($orders);
This is one option. try to dd($orders) an find if its working.
You had an another option like this, in your model
public function address()
{
return $this->hasMany(Address::class, 'refer_id', 'id');
}
Add relations like
public function billingAddress()
{
return $this->hasOne(Address::class, 'refer_id', 'id')->where('type', 1);
}
And
public function shippingAddress()
{
return $this->hasOne(Address::class, 'refer_id', 'id')->where('type', 2);
}
Then in your query,
$orders = Order::with('order_fulfillment', 'cart.product', 'user.address','user.billingAddress', 'user.shippingAddress', 'payment')->get(); return new OrderResource($orders);
So as I write at title I need to get all users who post offer to an admin user article...
So I write:
public function userbase()
{
return Offer::select('users.*')
->where('users.admin', 9)
->join('articles','articles.id','=','offers.article_id')
->join('users','users.id','=','articles.user_id')
->where('articles.user_id', Auth::user()->id)
->orderBy('offers.created_at', 'desc')
->groupBy('users.id')
->get();
}
but I get just [] (which is not true) ...
I also try:
public function userbase()
{
$user_ids = Article::where('user_id', Auth::id())
->join('offers')->on('offers.article_id', '=', 'articles.id')
->join('users')->on('offers.user_id', '=', 'users.id')
->select('users.id')
->distinct()
->get();
$users = User::whereIn('id', $user_ids);
return $users;
}
but I get:
Missing argument 2 for Illuminate\Database\Query\Builder::join()
attempt was:
public function userbase() { $articles = Auth::user()->articles()->get(); foreach ($articles as $article) {
$offers = Offer::where('article_id', $article['id'])->orderBy('created_at', 'desc')->get();
}
foreach ($offers as $offer) {
$users = User::where('id', $offer['user_id'])->orderBy('created_at', 'desc')->get();
}
return $users;
}
but offcource dont work...
Now I really dont know what to do next... PLEASE HELP...
also my MODEL:
Article:
public function offers() {
return $this->hasMany('App\Offer');
}
Offer:
public function user() {
return $this->belongsTo('App\User');
}
public function article() {
return $this->belongsTo('App\Article');
}
So how I can get users who post offer to other user(admin) article...
Try to put this function in the User model:
public function scopeBase($query){
$sql = <<<SQL
id IN(
SELECT DISTINCT users.id FROM articles
INNER JOIN offers
ON articles.id=offers.article_id
INNER JOIN users
ON users.id=articles.user_id
WHERE articles.user_id=? AND users.admin=?
)
SQL;
return $query->whereRaw($sql, [$this->id, 9]);
}
Then in the controller to get the users use this syntax:
class MyController extends Controller{
public function example(){
$users = User::base()->get();
//....
}
}
However if you explain better the table structure you will be grateful.
Did you try this?
foreach (User::all() as $user) {
foreach ($user->offers as $offer) {
if ($offer->article->user->isAdmin())
$select[] = $user;
}
}
I'm having trouble on the eager loading.
Let's say I have models of Members, TrainingCategory, TrainingCategoryResult and Registration
Member Model:
public function registration() {
return $this->hasMany('Registration', 'member_id');
}
public function trainingResults(){
return $this->hasMany('trainingResult', 'member_id');
}
public function trainingCategoryResults() {
return $this->hasMany('TrainingCategoryResult', 'member_id');
}
TrainingCategory Model:
public function trainings() {
return $this->hasMany('Training', 'id');
}
public function trainingCategoryResults() {
return $this->hasMany('trainingCategoryResult', 'category_id');
}
TraningCategoryResult Model:
public function category() {
return $this->belongsTo('TrainingCategory', 'id');
}
public function member() {
return $this->belongsTo('Member', 'id');
}
Registration Model:
public function course() {
return $this->belongsTo('Course', 'course_id');
}
public function member() {
return $this->belongsTo('Member', 'id');
}
I am trying to eager load all the registration info and its related info including the TraningCategoryResult info but I not sure how to get that TraningCategoryResult which required two foreign keys (category_id and member_id), is there any way to do that?
Here is my code atm:
$members= Member::where(function($query) use ($id, $site) {
$query
->where('id', '=', $id)
->where('site', '=', $site);
});
$members= $members
->with('registration.course',
'registration.course.traningCategories',
->get(['member.id']);
Thank you.
This will not work Member::with('categoryResult')->with('registration')->get()
You can make a new relation in Member Model
public function categoryResult()
{
return $this->belongsTo('Category')->with('Registration');
}
//and then call
Member::with('categoryResult')->get();
You could use a few options to achieve that:
OPTION 1: create a variable relationship
Change your relation in the Member model
public function trainingCategoryResults($category_id = null) {
if(empty($category_id))
return $this->hasMany('TrainingCategoryResult', 'member_id');
else
return $this->hasMany('TrainingCategoryResult', 'member_id')
->where('category_id', $category_id);
}
The code above might have limitations and it doesn't take advantage of many laravel features, but it will work.
OPTION 2: Access from relationship
You can keep everything as is, and load as follow:
$members= Member::where(function($query) use ($id, $site) {
$query
->where('id', '=', $id)
->where('site', '=', $site);
})
->where('id', $member_id) // set the id of the memeber
->with(array(
'traningCategoryResults' => function($q)use($category_id){
$q->where('category_id', $category_id); // This makes sure you get only desired results
}
))
In this way you will have only what you need, assuming you know the $category_id