Pass two id's in find query to update status database in laravel 4.2 - laravel-4

public function index($establishment_id,$subcat_id)
{
EstablishmnetSubcategories::find($establishment_id)->update('status',1);
echo "success";
}
This is my controller code, i want to update a column value with status = 1, but i have to verify with two id's if it matches then only it should get update.
i am not getting how to pass two id's in find query.
Can anyone please help me ..thank you

Try this query:
EstablishmentSubcategories::where('establishment_id', $establishment_id)
->where('subcategory_id', $subcat_id)
->update(['status' => 1]); // add update on update query in your query no where update
echo "success";

Related

Laravel eloquent relationships : difference betwen auth()->user()->favorites()->get() and auth()->user()->favorites

User Model :
public function favorites()
{
return $this->hasMany(Favorite::class);
}
Controller :
//return auth()->user()->favorites()->get();
//return auth()->user()->favorites;
can someone explain the difference betwen the two codes ?
and when i should use each one?
Let me explain it practically:
If the above query looks like this
// return auth()->user()->favorites()->where('active', true)->get();
// return auth()->user()->favorites->where('active', true);
then its SQL query be like this
// SQL of first query
select * from `favorites` where `favorites`.`user_id` = 1 and `favorites`.`user_id` is not null and `active` = 1
// SQL of second query
select * from `favorites` where `favorites`.`user_id` = 1 and `favorites`.`user_id` is not null
Did you see differences in two SQL?
Now, Let me explain it in words:
If you add some condition after favorites() like above, it will fetch all filtered result from database. But if you add some condition after favorites it will filter the result which is already fetched from the database.
Although, I'm not good at explanations, I hope you understand clearly between the two codes.

How can i limit my update function on Laravel 8?

I need to do an update, and I can't get it to work. I want to update my 'TIME' to right now on my last inserted row of 'number'. Everything works, but it saves on every row that matches 'number', and not only the last. This is the only error I'm getting. I have tried everything, and nothing solves my problem. However, I believe it is has a simple solution.
public function update()
{
DB::table('register')
->where('number', $this->number)
->limit(1)
->orderByDesc('id')
->update(['time' => date('Y-m-d H:i:s')]);
}
You cannot directly limit an UPDATE statement, it will run on every record matching your conditions.
In order to achieve what you're trying to do you have to find which record is the latest one and then directly update it.
The easiest way you can do it is with two different queries:
// Get the latest record on the "register" table
$latest = DB::table('register')
->where('number', $this->number)
->limit(1)
->orderByDesc('id')
->first(); // <-- Executes the query and returns the first element
// Update it with the current time
if ($latest !== null) { // <-- $latest could be null if the "register" table is empty
DB::table('register')
->where('id', $latest->id)
->update(['time' => date('Y-m-d H:i:s')]);
}
DB::table('register')
->where('number',$this->number)
->latest('id')
->limit(1)
->update(['time' => Carbon::now()]);
Edit: Latest by default sorts descending by column created_at. You can override that and pass the column you wish. ie: latest('id')

Does "where" works with mutattors in eloquent?

I have a mutattor in an eloquent model that generates a "status" atribute.
public function getStatusAttribute(){
if(){
return "enabled";
}
else
{
return "disabled";
}
}
Can I use?
$query = Anuncio::query();
$query->where('status', "enabled" );
return $query->get();
I seems that I cannot. I getting "status" column not defined. How can I get around this problem?
No doesn't works it works on model level
you can use after query from database in collection result
No, when you are doing a query you are asking the database, therefor there needs to be a column status.
There is a way, retrieve x elements from the database and use the Laravel Collection method where(). This is not optimal if you have many elements in teh database, it will retrieve all of them.
Anuncio::all()->where('status', 'enabled')->all();

Get specific values from controller function

I started learning Laravel and I am trying to achieve the following:
Get data from database and display specific field.
Here is my code in the controller:
public function show()
{
$students = DB::select('select * from students', [1]);
return $students;
}
Here is my route code:
Route::get('', "StudentController#show");
That all works for me and I get the following displayed:
[{"id":1,"firstname":"StudentFirstName","lastname":"StudentLastName"}]
How can I get only the "lastname" field displayed?
Thanks in advance!
DB::select('select * from students')
is a raw query that returns an array of stdClass objects, meaning you have to loop through the array and access properties:
$students[0]->lastname
You can also use the query builder to return a collection of objects:
$collection = DB::table('students')->get();
$student = $collection->first();
$student->lastname;
Lastly, using the query builder, you can use pluck or value to get just the last name. If you only have one user, you can use value to just get the first value of a field:
DB::table('students')->where('id', 1)->value('lastname');
I strongly advise you to read the Database section of the Laravel docs.
$students[0]['lastname'] will return the last name field, the [0] will get the first student in the array.
I would recommend creating a model for Students, which would make your controller something like this:
$student = Students::first(); // to get first student
$student->lastname; // get last names
If you only want the one column returned, you can use pluck()
public function show()
{
$last_names= DB::table('students')->pluck('lastname');
return $last_names;
}
This will return an array of all the students' lastname values.
If you want just one, you can access it with $last_names[0]
As a side note, your show() method usually takes a parameter to identify which student you want to show. This would most likely be the student's id.
There are several ways you can accomplish this task. Firstly, I advise you to use the model of your table (probably Students, in your case).
Thus, for example,to view this in the controller itself, you can do something like this using dd helper:
$student = Students::find(1);
dd($student->lastname);
or, using pluck method
$students = Students::all()->pluck('lastname');
foreach($students as $lastName) {
echo $lastName;
}
or, using selects
$students = DB::table('students')->select('lastname');
dd($students);
Anyway, what I want to say is that there are several ways of doing this, you just need to clarify if you want to debug the controller, display on the blade...
I hope this helps, regards!

Laravel eloquent query with sum of related table

I have a table users and posts with columns user_id and post_views.
In post_views I keep information how many times post was display.
And now, in query I would like to get user with sum of post_views all his posts.
I tried do something like this:
User::where(['id'=>$id])->with('posts')->get();
And in model I defined:
public function posts()
{
return $this->hasMany('App\Models\Post')->sum('post_views','AS','totalViews');
}
But without success.
How to do it?
Thank you
You can use a modified withCount():
public function posts()
{
return $this->hasMany('App\Models\Post');
}
$user = User::withCount(['posts as post_views' => function($query) {
$query->select(DB::raw('sum(post_views)'));
}])->find($id);
// $user->post_views
You can use
User::withCount('posts')->find($id)
to get the user with the id $id and a posts_count attribute in the response
I'm not fully sure what the intention of ->sum('game_plays','AS','totalVies'); is - you would need to add more context if you want this
Just something to add with regards to your shown code: No need to query by id using where + the get() at the end will make you query for a collection. If you want to get a single result use find when searching by id
As always laravel has a method for that : withSum (Since Laravel v8)
Note : I know that at the time of the message was posted, the method did not exist, but since I came across this page when I was looking for the same result, I though it might be interesting to share.
https://laravel.com/docs/9.x/eloquent-relationships#other-aggregate-functions
In your case it should be :
$user = User::withSum('posts as total_views', 'post_views')->find($id);
Then you can access to the result :
$user->total_views

Resources