Trying to delete table row laravel - php

I'm trying to delete table row by table cell ID.
I have a table called "server_admins". With table cell unique ID.
public function admins_delete($id)
{
$serveradmins = DB::table('server_admins')->first();
$serveradmins->delete($id);
return Redirect::to("/admin/servers/admins");
}
Route:
ModuleRoute::post('admin/servers/admins/delete/{id}', 'AdminServersController#admins_delete');
And my view:
But does not work at all... Any info? I'm new with laravel, so im kind a noob on that :) Sorry for dumb ask and thanks for helping me understand laravel.

Try this
Model::where('id',$id)->delete();; // Eloquent approach
DB::table('server_admins')->where('id',$id)->delete(); // Query Builder approach

You can directly chain like this if you know the primary key of the model.
DB::table('server_admins')->destroy($id);
Another method is to call the delete method on after retrieving the model.
$admin = DB::table('server_admins')::find($id);
$admin->delete();

Related

Can't access data from the Users table from a function in controller

I'm trying to use a function to soft delete 2 rows in a database, one is from a table I made called persona and the other one is from the users table that laravel makes with Auth, My users table have a foreign key associated to the persona table called idPersona. What I'm trying to do is to soft delete the row from the persona table that matches the id parameter and after that soft delete the row in users where the attribute idPersona matches the id parameter that the function recieved.
I'm going to post the Controller function code
Controller function code
public function deleteMedico($id){
$medico = Persona::findOrFail($id);
$medico->estado =False;
$personaID = $medico->id;
$user= new User();
$user->where('idPersona',$personaID);
var_dump($user);
}
I'm going to try to explain what I'm trying to do with this controller, I use the findOrFail function to find the row I'm trying to self delete from the persona table, after I found it I set estado to false in this way soft deleting the row. After that I try to get an User instance, look for the users table where idPersona matches the id of the row that was soft deleted.
The code for self deleting it would be almost the same than with the persona table but the problem is I can't find the row in the users table, gonna post the var_dump I get of $user.
Also gonna post how my database looks in case it is useful
I have no idea what I need to do to get the row of the users table where the idPersona attribute matches the id attribute from the personas table. I'm new in Laravel so sorry if this question is repetitive or is nothing to hard. p
Your syntax is wrong.
// $user = new User();
// $user->where('idPersona',$personaID);
$user = User::where('idPersona', $personaID)->firstOrFail();
This should fix the syntax but there are simpler ways to do this in your code.
Route model binding
Route::get('deleteMedico/{persona}', ...);
Eloquent Relationships
// Persona.php
public function user()
{
return $this->hasOne(User::class, 'idPersona');
}
public function deleteMedico(Persona $persona)
{
$persona->fill(['estado' => false])->save();
$persona->user->fill(['estado' => false])->save();
}
You forgot the get method.
User::where('idPersona',$personaID)->get();

Laravel. Get data from pivot table

How can i get data from pivot table directly (with Laravel)?
I have model \App\Model\Orders
class Orders extends Model
{
public function related_orders()
{
return $this->belongsToMany(\App\Model\Orders::class,'related_orders','order_id','related_id');
}
}
oK, i can get data from pivot table as
$order = \App\Model\Orders::find(1);
foreach ($order->related_orders as $related_order) {
$related_order->pivot->related_id;
}
But, i need only related order id! I don't want retrieve all related orders for get one id field. It's irrationally.
Can you help me?
PS: I know how do it with sql query it's no problem. I wonder how to do this with Laravel.
What you want to do seems pretty simple if I'm understanding correctly. If you want an array of ID's for the related orders, just do this:
$relatedOrders = $order->related_orders->pluck('id');
Let me know if that's what you meant and if that gives the correct result, perhaps there's something more you're looking to do that I didn't understand.
You can try this:
Get a specific order (in this case, 1):
$order = \App\Model\Orders::find(1);
Get the related order for the above order:
$relatedOrders = $order->related_orders->first();
Get the ID (assuming your column is id)
return $relatedOrders->id;

laravel update and select

I have a situation to update the row based on id and return the complete row. I can do it in two queries but i want to do it in one query only. I have write this...
$result= DB::table($this->table)
->whereRaw($where['rawQuery'], $where['bindParams'] ? $where['bindParams'] : array())
->increment($updateField);
if($result){
return DB::table($updateTable)
->select('id')
->where('campaign_id',$where['bindParams'])
->where('date',date("Y-m-d"))
->get();
}else{
throw Exception("Error in fetching data");
}
I copied this from what you commented in your question:
No i want to return the id of the updated row or complete row if possible
If you want to return the ID of the just updated 'row' you're talking about. You can use Eloquent to accomplish this.
You can use a route like this:
Route::put('demo/{id}', Controller#update);
Then in your update function in your controller you can get the ID.
Find the model with $model = Model::find(id);
do things with the data you get.
Like $model->name = Input::get('name');
Then use $model->save();
After saving you can do $model->id;
Now you get back the ID about the row you just updated.
Refer back to this question:
Laravel, get last insert id using Eloquent
But any way it'll always be at least 2 queries (a SELECT and an UPDATE in MySQL, however you do it)
You can check Laravel Eloquent if you want a "cleaner" way to to this.

Intermediate Table with Laravel

I'm working in a Webapp and I have a problems to work with a intermediate table, these are my tables in mysql:
User:
Integer:id
String:name
String:email
String:phone
Exercise:
Integer:id
String:name
String:description
User_Exercise:
Integer:id
Integer:id_user
Integer:id_exercise
Integer:record
So, what I want to do is that when I create an exercise, it be created one row for each user with the exercise-id that I have created it before. Later the user could change his record in this exercise.
I have thought to create a model to handle the user_exercise's table but I don't know if there is some way to do this better or not.
So, There are some way to do this without create a new model?
PD: Sorry for my terrible english
You don't need a seperate model for User_Exercise
You can use $this->belongsToMany from base Model i.e., User
Note :
For insert process you can get the parent id by
$insertUser = User::create($userData);
then
$insertUser->id for taking the last insert id
And then to retrieve with respect to User_Exercise you shall use $this->belongsToMany from your User Model
Example
Have this in your User Model
public function getUser() {
return $this->belongsToMany('App\User', 'excercise_name', 'user_id', 'excercise_id')->select(array('exercise.id', 'excercise.name'));
}
And Get the data you need from any Controller like this
$userData = User::find($userId)->getUser;

If exist Update else Insert Into. MySQL - PHP

I'm asking this question in order to find the best practice to do it.
DB::table('owners')
->where('property_id',$id)
->update(array('person_id'=>$owner));
The problem is that in the table owners might not have a row to update. In that occasion i need to make an INSERT INTO instead of UPDATE.
My problem is that i have to run 2 queries each time, one for checking if the row already exists, and one more to update or insert into. Is it right to run 2 queries each time? Is there a better way to achieve that? I need to keep the queering processes fast for the user.
UPDATE: The table owners is a middle table of a many to many relationship. Unfortunately i cannot use ON DUPLICATE KEY.
well you could try to use firstOrCreate method of Laravel to check if user exists. After that retrieve the user object and pass it to an update function else if the user is not found firstOrCreate method will take care of you as it will create a new user with the data you will provide and will auto increment last user + 1 id.
There is also the option to use firstOrNew which will check if an instance exists based on the array values you passed and if no match is found it will auto create a new instance of the model you are handling for further manipulation.
Here is example with firstOrNew
Example Controller file.
public function getFirstUserOrNew($email)
{
$user = User::firstOrNew(['email' => $email]);
if($user)
{
$this->UpdateUser($user);
}
else
{
$this->CreateUser($user);
}
}
public function UpdateUser(User $user)
{
//Do update stuff
}
public function CreateUser(User $user)
{
//Do create stuff
}
P.S - I'm from Greece, if you want to discuss anything in native language send me a PM :)
EDIT:
Thanks to #Pyton contribution It seems you can also use an updateOrCreate method as it is explained here.
If you want to Update or Insert row You can use updateOrCreate
$owner = Owner::updateOrCreate(['property_id' => $id], ['person_id'=>$owner]);

Categories