Laravel 5 - SoftDelete not working - laravel

I've been searching a lot in the web and StackOverflow itself, however I can't find a solution to the problem.
Soft deleting simply refuses to work. The database has the deleted_at field. User model has everything needed to supposedly work, however data is still hard deleted when I call the Delete() method. I don't know what I'm doing wrong.
Laravel Version: 5.3.31
destroy method
public function destroy($id)
{
//$this->authorize('delete', User::class);
$user = User::find($id);
if (empty($user)) {
Flash::error('User not found');
return redirect(route('users.index'));
}
$user->Delete();
Flash::success('User deleted successfully.');
return redirect(route('users.index'));
}
user model
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes;
public $table = 'users';
const CREATED_AT = 'created_at';
const UPDATED_AT = 'updated_at';
protected $dates = ['deleted_at'];
public $fillable = [
'name',
'email',
'password',
'role',
'remember_token'
];
protected $casts = [
'id' => 'integer',
'name' => 'string',
'email' => 'string',
'password' => 'string',
'role' => 'string',
'remember_token' => 'string'
];
public static $rules = [
'name' => 'required|max:255',
];
}
I appreciate anything that can help me to solve this.
Thanks in advance.

Related

Problems with Laravel and validation

Im building CRUD for my application in Laravel 9. I defined some fields in my database as NOT NULL. Those values will be completed by code at the time a new user is created.
The first field Im dealing with is 'creado' (same as 'created at' in english) field (and I dont want to use built in timestamp)
User model:
public $timestamps = false;
protected $fillable = [
'username',
'password',
'apellidos',
'nombres',
'tipoDocumento',
'nroDocumento',
'cuit',
'cuil',
'fechaNacimiento',
'sexo',
'domicilio',
'domicilioNro',
'domicilioPiso',
'domicilioDepto',
'localidad',
'codigoPostal',
'telefonoFijo',
'telefonoCelular',
'telefonoAlt',
'email',
'creado', //This is the value
];
protected $hidden = [
'password',
'password_repeat', //This value is still being displayed in error msg...
'remember_token',
];
protected $casts = [
'creado' => 'datetime', //Dont think its necessary
];
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
public function setCreadoAttribute()
{
//This method never get called...
$this->attributes['creado'] = date("Y-m-d H:i:s");
}
RegisterRequest:
public function rules()
{
return [
'username' => 'required|unique:clientes,username',
'password' => 'required|min:8',
'password_repeat' => 'required|same:password',
'apellidos' => 'required',
'nombres' => 'required',
'fechaNacimiento' => 'required',
'sexo' => 'required',
'tipoDocumento' => 'required',
'nroDocumento' => 'required|unique:clientes,nroDocumento',
'cuil' => 'nullable|min:11|max:11',
'cuit' => 'nullable|min:11|max:11',
'domicilio' => 'required',
'domicilioNro' => 'required',
'localidad' => 'required',
'codigoPostal' => 'required',
'telefonoCelular' => 'required',
'email' => 'required|unique:clientes,email',
'creado' => 'nullable|date',
];
}
Controller:
public function register(RegisterRequest $request)
{
$cliente = Clientes::create($request->validated());
return redirect("login")->with("success","Bla Bla Bla");
}
In view, all fields are present, except 'creado'. If I add input type text named creado, it works. Else the field its not included in the query. I dont know why its not working when I marked it as nullable.
$casts array and setCreado can be removed.
Then, you can use an accessor, in your model:
protected function creado(): Attribute
{
return Attribute::make(
get: fn ($value) => date("Y-m-d H:i:s"),
);
}
Mas info ;) Accessors
Importante this:
This method name should correspond to the "camel case" representation of the true underlying model attribute / database column when applicable.
Finally, I was able to fix this using this approach:
In ClientsController
public function register(RegisterRequest $request)
{
$cliente = new Cliente;
$cliente = Cliente::make($request->validated());
$cliente->setCreadoAttribute();
$cliente->save();
return redirect("login")->with("success","Cuenta creada exitosamente");
}
In Client model:
public function setCreadoAttribute()
{
$this->attributes['creado'] = date("Y-m-d H:i:s");
}
Im not really sure if this is the best way or the best practice to accomplish what I was needing, but for now it works.
From the docs
If you need to customize the names of the columns used to store the timestamps, you may define CREATED_AT and UPDATED_AT constants on your model:
<?php
class Flight extends Model
{
const CREATED_AT = 'creation_date';
const UPDATED_AT = 'updated_date';
}

Can't proceed to checkout - Call to a member function checkout() on null

I'm trying to charge a customer in my Laravel app but it keeps saying $customer is null. Any idea what's wrong?
The error:
Call to a member function checkout() on null refers to this line return $customer->checkout...
However calling echo $id returns the customer ID so I see no issue why findBillable returns a null object.
The customer does indeed exist in Stripe and hard-coding the ID doesn't change anything.
use Laravel\Cashier\Cashier;
$user = new App\Competitor();
$stripeCustomer = $user->createAsStripeCustomer([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
]);
$id = $user->stripeId();
$customer = Cashier::findBillable($id);
return $customer->checkout(['price_foobarfoobar' => 1], [
'success_url' => 'https://staging.domain.com/thank-you',
'cancel_url' => 'https://staging.domain.com/sign-up',
]);
Competitor.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Laravel\Cashier\Billable;
class Competitor extends Model
{
use Billable;
protected $table = 'competitors';
protected $fillable = [
'name',
'email',
'phone',
'selected_event',
'team_name',
'user_agent',
'ip_address',
'created_at',
'stripe_transaction',
'stripe_id',
];
}
Had to inform Cashier I was using a different Billable model...
Cashier::useCustomerModel(Competitor::class);

Laravel update eloquent not updating the record

I am using Laravel eloquent to update the record. The problem is the update method returns the integer equal to number of records should be updated but this update is not being reflected in database.
I inserted some records to check there is no database mismatch.
I am even using fillable method and defined every column into it.
Here is my code.
Modal
protected $fillable = [
'id',
'user_id',
'ticket_no',
'partner_id',
'partner_user_name',
'partner_user_email',
'partner_user_contact',
'contacted_for_id',
'issue_type_id',
'comm_mode_id',
'opened_by_id',
'assigned_to_id',
'team_id',
'priority_id',
'opened_date',
'tat_id',
'resolved_date',
'status_id',
'description',
];
Controller
public function update(Request $request)
{
$validators = Validator::make($request->all(), [
'assigned_to_id' => 'required',
'team_id' => 'required',
'resolve_date' => 'required',
'status_id' => 'required',
'description' => 'required',
]);
if ($validators->fails()) {
$data['result'] = false;
$data['messages'] = $validators->errors()->first();
return json_encode($data);
}
$assigned_to_id = $request->assigned_to_id;
$team_id = $request->team_id;
$resolve_date = $request->resolve_date;
$status_id = $request->status_id;
$description = $request->description;
$ticket_row_id = $request->ticket_row_id;
$updated = TICKET_TRACKER::where('id', $ticket_row_id)
->update(
['assigned_to_id' => $assigned_to_id],
['team_id' => $team_id],
['resolve_date' => $resolve_date],
['status_id' => $status_id],
['description' => $description]
);
}
I am not getting any error that's the most frustrated thing.
In order to make your model to be updated change:
$updated = TICKET_TRACKER::where('id', $ticket_row_id)
->update(
['assigned_to_id' => $assigned_to_id],
['team_id' => $team_id],
['resolve_date' => $resolve_date],
['status_id' => $status_id],
['description' => $description]
);
By:
$updated = TICKET_TRACKER::where('id', $ticket_row_id)
->update([
'assigned_to_id' => $assigned_to_id,
'team_id' => $team_id,
'resolve_date' => $resolve_date,
'status_id' => $status_id,
'description' => $description
]);
In fact you need to have only one array with keys and values in order to view your model updated.
[EDIT 1]
As said in the comments in Laravel you need to take care about naming conventions,
If the name of the model is TicketTracker, the name of the table should be plural. So it will be ticket_trackers.
or if you want to have a custom name for your table you can configure in your model the $table property as follows:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class TicketTracker extends Model
{
protected $table = "other_table_name"
}

Call to a member function details() on null?

My code is:
$user = User::create([
'email' => $request->email,
'password' => Hash::make($request->password),
]);
$user_details = [
'name' => $request->name,
'address' => $request->address,
'lastname' => $request->lastname,
'secondname' => $request->secondname,
'inn' => $request->inn,
'fincode' => $request->fincode,
];
$user->details()->create($user_details);
Model User is:
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
public function details()
{
return $this->hasOne(UserDetails::class, 'user_id', 'id');
}
}
UserDetails model is:
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserDetails extends Model
{
protected $table = 'enterprise';
protected $fillable = ['name', 'lastname', 'secondname', 'address', 'inn', 'fincode'];
}
I believe that your $user has not been persisted, hence having the error, in your case $user is null, that's why you cannot call details on null object. Make sure that you use all the required fields on your user.
You might be missing the fillable array in the User model if the one that you shared is the full content, then add this:
protected $fillable = [ 'email', 'password'];

Data not saved in database in real after model created

I am using CREATE method for mass assignment in laravel eloquent, the result also printed and showing, but when i check table in database, no data inserted.
I am using laravel 5.6, It showing successful, but in real no data saved in table.
here is my code
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
protected $table = 'users';
public $primaryKey = 'user_id';
public $timestamps = false;
protected $fillable = [
'first_name','middle_name', 'last_name', 'role_id', 'email', 'mobile', 'telephone'
];
.... and other code
Here is my insert function
$users = User::create([
'first_name' => $row[1],
'middle_name' => $row[2],
'last_name' => $row[3],
'email' => $row[4],
'role_id' => 6,//$row[5],
'telephone' => $row[6],
'mobile' => $row[7],
]);
var_dump($users);// this shows result.
$users prints data. There is no error showing. BUT when i check database, table is empty. I expect the same data in users table.

Resources