I want to get only the last inserted data from my database.
Here, I get all data from the database but I want only the last value.
This is ProductController.php
function indextwo()
{
return DB::select("select * from products");
}
This is web.php
Route::get('products_link', [ProductController::class, 'indextwo']);
Here is my current output:
You can get the last id using Query Builder and Eloquent.
Query Builder
function indextwo() {
return DB::table('products')->orderBy('id', 'DESC')->first();
}
Eloquent
function indextwo() {
return Product::orderBy('id', 'DESC')->first();
}
Maybe you can use latest() function for get
$user = DB::select("select * from products")
->latest()
->first();
Maybe you can use Model name direct in controller like your model name is "Product" and also use limit() and latest()
$user = Products::latest()->limit(1);
A very simple way you can follow
Product::query()->latest()->first()
It will return you the latest inserted data according to order by id desc.
Another way :
Product::query()->orderByDesc('id')->first();
Related
I want to join multiple tables in laravel with query builder. My problem is that my code only works if I specify the id myself that I want like this:
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=','1')
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
But I would want something like this(which I just can't seem to figure out)
public function showuser($id)
{
$userid = User::findOrFail($id);
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$userid)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
}
Am I making a syntax mistake? When I check the page for my json response in second page it just returns empty brackets, but when I specify the id it fetches me the right data
The findOrFail method will return the entire user model, with all its properties, since you already have the user id. You dont need to get the entire user model for that, you could just use the $id you receveid as a parameter like this:
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$id)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
public function showuser($id)
{
$getUserByID = User::findOrFail($id); //not used
$userData = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$id)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($userData);
}
But the best way is to have relations set on models
public function showuser($id)
{
$userData = User::where('id', $id)->with(['activitates','taga_cars','clients'])->first();
return response()->json($userData);
}
I have created a one-to-many relationship. Here are the model classes.
class Photo extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
}
class User extends Authenticatable
{
public function photos(){
return $this->hasMany('App\Photo');
}
}
Then I try to retrieve photos:
$photos = User::find(1)->photos->where('photo', 'ut.jpg')->first();
Here is a query log I got. I do not see the photo='ut.jpg'. So how laravel generate SQL?
select * from `photos` where `photos`.`user_id` = 1 and `photos`.`user_id` is not null
Try this
$photos = User::find(1)->photos()->where('photo', 'ut.jpg')->first();
must be use ->photos() instead of ->photos.
For see sql query use
$sql = User::find(1)->photos()->where('photo', 'ut.jpg')->toSql();
You queried all photos by using this:
$photos = User::find(1)->photos->where('photo', 'ut.jpg')->first();
By using User::find(1)->photos you receive a Laravel Collection. Those collections have a where method as well. So basically, you are running SQL to get all photos of User 1 and then you just filter that collection to only show you the item with photo ut.jpg.
Instead, you can use brackets to get the relationship, and then query that.
Your query then becomes
$photos = User::find(1)->photos()->where('photo', 'ut.jpg')->first();
Instead of naming it $photos you should name it $photo, as you are querying with first - which will result only in one object (or null).
Can you please try this:
$photo = 'ut.jpg';
$photos = User::find(1)->whereHas('photos', function ($query) use($photo){
return $query->where('photo', $photo);
})->first();
your query $photos = User::find(1)->photos->where('photo', 'ut.jpg')->first(); is incorrect, laravel didnt see the where condition if you do this
User::whereHas('photos', function($q) {
$q->where('photo', 'ut.jpg');
})->where('id',1)->first();
thats the correct query to get the user photo
You could:
Run A Select Query
$photos = DB::select('select * from photos where id = ?', [1]);
All this is well-documented in :
--https://laravel.com/docs/5.0/database
I'm trying to loop through the items using eloquent in laravel but I'm getting 0. Please see my code below.
Model
Class Store{
public function products(){
return $this->hasMany('App\Product');
}
}
Controller
$products_count = 0;
foreach($store->products() as $product)
{
if($product->status == 1)
{
$products_count++;
}
}
dd($products_count);
Note: I have data in my database.
You can also use withCount method something like that
Controller
$stores = Store::withCount('products')->get();
or
$store = Store::where('id', 1)->withCount('products')->first();
WithCount on the particular status
$stores = Store::withCount(['products' => function ($query) {
$query->where('status', 1);
}
])
->get();
ref: withcount on relationship
That's because $store->products() returns an eloquent collection which doesn't contain the data from the database yet. You need to do $store->products instead.
If you need to get the count from the database then use
$store->products()->where('status', 1)->count()
With the function-annotation (i.e. products()) you are retrieving the \Illuminate\Database\Eloquent\Builder-instance, not the actual Eloquent-collection.
Instead, you would have to use $store->products – then you will get retrieve the related collection.
In Laravel $store->products() makes you access the QueryBuilder instance, instead there is the Laravel way of doing $store->products, which loads the QueryBuilder and retrieves the collection automatically and down the line is easy to optimise.
I am fetching records in controller :
$tasks = Task::where('user_id', '=', Auth::user()->id);
return view('todo',compact('tasks'));
But it returns null.
And Auth::user()->id returns 2 Which is Okay.
Am i missing something ?
You need to actually retrieve the record. What you have is an instance of \Illuminate\Database\Eloquent\Builder, but not the actual record(s) associated with the query.
To tell Eloquent to fetch the data, you need to use either get().
Like:
$tasks = Task::where('user_id', '=', Auth::user()->id)->get();
As a side note, you can simplify your query to be:
$tasks = Task::where('user_id', Auth::user()->id)->get();
Furthermore, on your User model, you could do this:
public function tasks()
{
return $this->hasMany(Task::class) // make sure you use the full namespace here or use at the top of User.php
}
And then you can simply do:
$tasks = auth()->user()->tasks;
This is a Relationship in Eloquent as explained in the docs.
how can I sort the return data from a query using whereHas? In my query i have to get the users data which id exist on interest table but i need to sort it using the datetime column from interest. But, the return query do not sort the data at all.
Here's my code snippets in case it would help you understand my problem.
Model (name: User)
//***relationship***//
public function interest(){
return $this->belongsTo('Interest','id','interest_by');
}
Controller
$userInterested = User::whereHas('interest',function($q) use ($id) {
return $q->where('interest_on', $id)
->orderBy('datetime');
});
$userQuery = $userInterested->get();
return $userQuery;
remove return from where has and try this.like
$userInterested = User::whereHas('interest',function($q) use ($id) {
$q->where('interest_on', $id)
->orderBy('datetime');
})->get();
return $userInterested;
$userInterested = User::whereHas('interest',function($q) use ($id) {
return $q->where('interest_on', $id);
})->orderBy('datetime');
$userQuery = $userInterested->get();
return $userQuery;