Select data by status column in laravel 5 - php

IN Custom php code
$select_query = "select * from admin where Stutes = '1' order by ID asc";
How we can embed this code in my this laravel 5 code
public function index()
{
$books=Book::all();
return view('books.index', compact('books'));
}

You can use the Query builder
$admin= DB::tabe('admin')
->select("*")
->where("Stautes",1)
->orderBy("ID", "asc")
->get();

Optimised Query:
Since you are trying to retrieve all rows your query can be likewise:
$admin= DB::table('admin')->where("Status",1) ->orderBy("ID", "asc") ->get();
If you want to retrieve a specific column:
$admin_ids = DB::table('admin')->select('id')->where("Status",1) ->orderBy("ID", "asc") ->get();
Laravel Select docs
Hope this helpful.

In controller
public function index()
{
//$books=Book::all();
$books= DB::table('books')
->select('*')
->where('status', '1')
->orderBy('id', 'asc')
->get();
return view('books.index', compact('books'));
}

Related

Laravel and PHP - Condition in the SQL request

I have a query
$BaseUsers = DB::table('users', 'users.ustatus', '=', '1')
->join('user_infos', 'user_infos.user_id', '=', 'users.id')
->select('users.*', 'user_infos.add1', 'user_infos.add3')
->paginate(3);
It work fine. But i need insert condition "where" to search in result
i send $request from form. How insert condition to query?
In PHP it looks like this:
if($request['add_1'])
{
$insert1=" and add_1<>'' ";
}
if($request['add_2'])
{
$insert2=" and add_2<>'' ";
}
...
$sql=" SELECT users.*, user_infos.add1, user_infos.add3 FROM users JOIN user_infos where users.ustatus=1 and user_infos.user_id=users.id ".$insert1." ".$insert2."";
How can this be done on laravel in Controller? I mean - just insert the necessary condition insert1, insert2 ... into the query
you can use where() and has() to build your query
$query = DB::table('users');
if($request->has('age')) {
$query->where('age', '>', $request->age);
}
$query = $query->get();
I hope it's helpful
All is simple ) I use when in query
$BaseUsers = DB::table('users', 'users.ustatus', '=', '1')
->join('user_infos', 'user_infos.user_id', '=', 'users.id')
->when($request->input('f_add3'), function ($query) {
return $query->where('user_infos.add3', '<>', '');
})
->select('users.*', 'user_infos.add1', 'user_infos.add3')
->paginate(3);

Relationship eloquent in laravel?

In user:
public function posts()
{
return $this->hasMany(Post::class);
}
In post:
public function users()
{
return $this->belongsTo(Users::class);
}
I handle in controller:
$user = Users::find('1')->posts;
Then I get an array and the result returned is exactly what I need.
But when I query this way because I need to get a lot of data, the result is an empty array. What did I do wrong?
In UserController.php:
$listUser = Users::with('posts')
->select('name', 'title')
->where('type', 1)
->get(); // It returns posts as an empty array
Please give me any comments.
You have to select foreign key in posts:
$listUser = Users::select(['id', 'name'])
->with(['posts' => function($query) {
$query->select(['user_id','title']);
}])
->where('type', 1)
->get();
or
$result = User::select(['id', 'name'])
->with(['posts:user_id, title'])
->get();
Your relation is developed with a primary key and in your query you are missing the id to get the values.
$listUser = Users::with('posts')
->select('users.id', 'users.name', 'posts.title')
->where('posts.type', 1)
->get();
If you wish to select only some fields of the related model you can specify it in the with clause like the following. The select clause will work on the User query builder.
$listUser = Users::with('posts:user_id, title')
->select('name')
->where('type', 1)
->get();

How to use Eloquent model property in subquery?

I have two tables (users, posts) and I'm trying to order users according to recent post's date.
But unfortunately I couldn't find a way to use User model's firebase_id to use in subquery. I don't want to use raw query or DB directly if it's possible to use Eloquent for such query.
How can I use User model's firebase_id as subquery parameter?
Here is my non-working code to give an idea about what I try to do:
User::select('users.*', DB::raw("SELECT MAX(id) FROM posts WHERE posts.firebase_id = users.firebase_id as recent_post_date"))
->whereHas('posts', function ($q) {
$q->withCount('comments');
})
->with(['posts' => function ($q) {
$q->withCount('comments')
->orderBy('created_at', 'ASC');
}])
->orderBy('recent_post_date', 'DESC')
->get();
You can use selectSub to add a subquery.
Try the following
$recentPostQuery = Post::select('created_at')
->whereColumn('firebase_id', 'users.firebase_id')
->latest()
->limit(1)
->getQuery();
User::select('users.*')
->selectSub($recentPostQuery, 'recent_post_date')
->whereHas('posts', function ($q) {
$q->withCount('comments');
})
->with(['posts' => function ($q) {
$q->withCount('comments')
->orderBy('created_at', 'ASC');
}])
->orderBy('recent_post_date', 'DESC')
->get();
You can do with QueryBuilder and a join:
$users = DB::table('users')
->join('posts.firebase_id ', '=', 'users.firebase_id ')
->orderBy('posts.recent_post_date', 'DESC')
->get();
UPDATE
You asked for Eloquent. You can do it with whereHas.
$users = User::whereHas('posts', function (Builder $query) {
$query->orderBy('posts.recent_post_date', 'DESC');
})->get();

Combining inner join and where statements in Eloquent

I am trying to convert the following database query to use Eloquent:
$orderitems = DB::table('order_items')
->join('orders', 'orders.id', '=', 'order_items.order_id')
->where('orders.status', 1)
->where('order_items.sku', $sku)
->select('order_items.*')
->get();
I've tried the following:
$orderitems = Item::where('sku', $sku)
->with(['order' => function ($query) {
$query->where('status', 0);
}])
->get();
but it seems to be bringing back more results than it should. I can see from using DB::getQueryLog that the order_items query is not joining with the orders table:
select * from `order_items` where `stock_code` = ? and `order_items`.`deleted_at` is null
Do I need to create a new relationship between orderitems and order and add the additional where into that?
Relationships:
Order hasMany Items
Item hasOne Order
Solution was to use Query Scopes https://laravel.com/docs/5.7/eloquent#query-scopes
In the controller:
$orderitems = Item::stock($sku)->paginate(10);
In the orderitems model:
public function scopeStock($query, $sku)
{
return $query->join('orders', function ($join) {
$join->on('orders.id', '=', 'order_items.order_id');
$join->where('orders.status', '=', 1);
})
->select('order_items.*', 'orders.order_date')
->where('order_items.sku', $sku);
}

query raw inside groupBy in laravel 5.2

I have a problem with my query when I'm trying to group by Date(timestamp) in my laravel project, lets see my code.
RekapController#index
public function index()
{
$absen = Absen::groupBy(raw('DATE(created_at)'))
->orderBy('created_at', 'DESC')
->get();
return view('rekap.index')->with('data', $absen);
}
in my sql syntax is work perfectly
SELECT * FROM absen GROUP BY DATE(created_at) DESC
how can I fix this?
Edit:
The Error is
Call to undefined function App\Http\Controllers\raw()
you can try something like this
$absen = Absen::groupBy(\DB::raw('DATE(created_at)'))
->orderBy('created_at', 'DESC')
->get();

Categories