How to check if row is soft-deleted in Eloquent? - php

In Laravel 5.1 is there a nice way to check if an eloquent model object has been soft-deleted? I'm not talking about selecting data but once I have the object e.g. Thing::withTrashed()->find($id)
So far the only way I can see is
if ($thing->deleted_at !== null) { ... }
I do not see any relevant method in the API that would allow for example
if ($thing->isDeleted()) { ... }

Just realised I was looking in the wrong API. The Model class doesn't have this, but the SoftDelete trait that my models use has a trashed() method.
So I can write
if ($thing->trashed()) { ... }

In laravel6, you can use followings.
To check the Eloquent Model is using soft delete:
if( method_exists($thing, 'trashed') ) {
// do something
}
To check the Eloquent Model is using soft delete in resource (when using resource to response):
if( method_exists($this->resource, 'trashed') ) {
// do something
}
And finally to check if the model is trashed:
if ($thing->trashed()) {
// do something
}
Hope, this will be helpful!

For those seeking an answer on testing environment, within laravel's test case
you can assert as:
$this->assertSoftDeleted($user);
or in case it's just deleted (without soft deleting)
$this->assertDeleted($user);

This is the best way
$model = 'App\\Models\\ModelName';
$uses_soft_delete = in_array('Illuminate\Database\Eloquent\SoftDeletes', class_uses($model));
if($usesSoftDeletes) {
// write code...
}

This worked for me
$checkDomain = Domain::where('tenant_id', $subdomain)->withTrashed()->first();
if($checkDomain->trashed()){
return redirect()->route('domain.not.found');
}else{
return view('frontend.' . theme() . '.index');
}

Related

Laravel's Eloquent table 'inheritence' with parents

I have a Laravel model acl_groups that has a JSON column inherits. What should I do, the "laravel way" to query the inherited groups when checking if a group can do something? The rights are stored in another JSON column, allow/deny so I can just do a in_array to check a single group if they have access.
On your model you can set a getter
public function getInheritsAttribute($v)
{
return $v ? json_decode($v, true) : [];
}
OR
if you dont want a getter you can try a pseudo getter
public function getPseudoAttribute()
{
return $this->inherits ? json_decode($this->inherits, true) : [];
}
Kind of maybe did mistake on second one.
And on other model the same thing
so when you call $item->inherits = you will get an array
First you may try to prepare the array like removing same keys or values
and after just check
if (array_key_exists('thing_to_check', $item->inherits)) {
return true;
}
This is not a working code, it is just an idea how you can do you.
Take a look at Cartalyst Sentinel how they check the permissions for groups and users.

Laravel get property of non object

When I try to determine if an object is empty it's telling me:
Trying to get property of non-object
I'm doing it like this:
$lastTicket = Auth::user()->ticket->last()->ticketid;
if($lastTicket->isEmpty())
{
$lastTicket = 0;
}
Obviously Auth::user()->ticket->last(); isn't a record yet. How should I do this? I'm working with Laravel.
You need to check that collection not empty before get the property:
if(Auth::user()->ticket->last()->isEmpty())
{
$lastTicket = 0;
}
else
{
$lastTicket = Auth::user()->ticket->last()->lastId;
}
In short way:
$lastTicket = !Auth::user()->ticket->last()->isEmpty() ? $lastTicket = Auth::user()->ticket->last()->lastId : 0;
First of all have a look here if can be a solution at your problem. And anyway if you're trying to load a relation you should look at the official documentation:
Dynamic Properties
Eloquent allows you to access your relations via dynamic properties. Eloquent will automatically load the relationship for you, and is even smart enough to know whether to call the get (for one-to-many relationships) or first (for one-to-one relationships) method. It will then be accessible via a dynamic property by the same name as the relation. For example, with the following model $phone:
class Phone extends Eloquent {
public function user()
{
return $this->belongsTo('User');
}
}
$phone = Phone::find(1);
Instead of echoing the user's email like this:
echo $phone->user()->first()->email;
It may be shortened to simply:
echo $phone->user->email;
The right answer was:
$lastTicket = !Auth::user()->ticket->last() ? Auth::user()->ticket->last()->ticketid+1 : 0;
because if it's empty it will return 0 as default.

Is it possible to use models in laravel routes without static?

For example I need to return comments. I already have a method for this in my model. Is it possible to do something like this?
Route::get('/comments/{page}', function($page) {
$comments = Comments::get($page);
return Response::json($comments);
});
Or do I need to create a facade for each model?
Typically, comments would be associated with a page via an Eloquent relationship, which would allow something like this:
return Response::json($page->comments);
Check Defining A Query Scope on Laravel website:
// In Comments Model
public function scopeGetMessage($query, $page)
{
// You can use $query->where(...)
// return the query for chaining
// You can use $this->where(...)
// Or just return the thing you want
}
Now you may call it like:
$comments = Comments::getMessage($page);

CodeIgniter: return FALSE if Active Record can't find any data

Using CodeIgniter, I find the following code in all the models that gathers data from a database:
// .. taken from function get_user_data($user_id)
// Select data
$user_data = $this->db->from('users')->where('id', $user_id)->get()->row();
// Check if we got any matches
if(isset($user_data->id)) {
// Indeed we did, return the data found
return $user_data
} else {
// Nope, no data found
return FALSE;
}
The interesting part is where I check if the query actually returned any data. I'm doing that for EVERY query, which adds up to quite a bit repetitive code.
Is there any way to, perhaps override the CodeIgniter functions, making them return FALSE if no data was found?
I'm probably missing something, as I can't see why CodeIgniter isn't handling this already.
There isn't much in the way of built in shortcuts. Even the manual suggests checking your results:
If you run queries that might not produce a result, you are encouraged to test the result first:
$query = $this->db->query("YOUR QUERY");
if ($query->num_rows() > 0)
{
// found results
}
You could always use a class extension:
class MY_Model extends CI_Model {
protected function _get_row($result)
{
return $result->num_rows() ? $result->row() : FALSE;
}
}
Usage in a model:
function get_user_data($user_id)
{
$user_data = $this->db->from('users')->where('id', $user_id)->get();
return $this->_get_row($user_data);
}
You'd just have to extends MY_Model for the models you want to have access to the function.
Another option would be to return the result of $this->db->get() instead, and do the check in your controller (which you would probably have to do anyways).
I agree with wesley murch option but i think creating a entire class for an individual function isn't good practice. My opinion is to use helpers. You can try this:
In Helper File:
function get_db_data($result)
{
return ( $result->num_rows() > 0 ) ? $result->result_array() : false;
}
You can call this function in any of your model with
$this->load->helper('helper_file_name');
$dbData = get_db_data(result_object);

I would like to know if an object is in my Doctrine Collection

I'm working on Symfony 1.4 with Doctrine 1.2 and I have some problems.
I have created one Doctrine Collection of my Products like this :
$oProductCollection = new Doctrine_Collection('Products');
And I add some product in :
$oProductCollection->add($oMyProduct);
Then I want to know if a product is already in my Collection. Because if I add my product twice, that overwrite my old version...
I found "contains" function but I can't give my product object directly and I don't know what the key is...
Could you help me please ?
You can set the keyColumn by
//set the id column as key
$oProductCollection = new Doctrine_Collection('Products', 'id');
Then you can use $oProductCollection->contains($oMyProduct->getId()); to check whether $oMyProduct is already in your Collection.
Now you are able to write
if ($oProductCollection->contains($oMyProduct)){
echo "Its already in";
}else{
$oProductCollection->add($oMyProduct);
}
Another alternative. Index your collection by id, and just check if it exists. It should be pretty fast. Take a look at the docs.
Something like:
$id = $oMyProduct->getId();
if (!empty($oProductCollection[$id])){
...
}
You should implement a method Produits::equals(Produit $p) check every object of the collection using a loop.
foreach ($oListeProduit as $p) {
if ($p->equals($produit)) {
return true;
}
}
return false;
You have to use the second parameter of the Doctrine_Collection constructor:
public function __construct($table, $keyColumn = null)
So:
$oProductCollection = new Doctrine_Collection('Products', 'id');
And then contains with an id will work.
Edit: grilled :(

Categories