When I select all records using eloquent Model::all() method it's give me soft delete record too.
Model class
protected $table = 'tr_fl_tax_charges';
protected $primaryKey = 'fl_tax_id';
use SoftDeletes;
protected $softDelete = true;
protected $dates = ['deleted_at'];
Controller class
Case 1
public function index()
{
$tax = Tax::all();
return $tax;
}
it's give me all record including soft deleted row.
Case 2
public function index()
{
$tax = Tax::all()->where('deleted_at' , '=', null);
return $tax;
}
this case give me correct output and not including soft deleted rows but it's give me all the columns and I don't need all columns.I need only 4 columns.
Case 3
If I add column name that need in all() method it's give me soft deleted row too.
public function index()
{
$tax = Tax::all('fl_tax_id','fl_tax_type','fl_tax_name','fl_charge_type','fl_charge_rate')->where('deleted_at' , '=', null);
return $tax;
}
Case 4
If I add one more column deleted_At in case 3 it's give me expected output.
public function index()
{
$tax = Tax::all('fl_tax_id','fl_tax_type','fl_tax_name','fl_charge_type','fl_charge_rate', 'deleted_at')->where('deleted_at' , '=', null);
return $tax;
}
What I want is I want only those record which is not soft deleted and from those records I want to select columns. How ?
UPDATE WITH MODEL AND CONTROLLER FILES
Tax.php (Model) - here BaseModel extends Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
class Tax extends BaseModel
{
protected $table = 'tr_fl_tax_charges';
protected $primaryKey = 'fl_tax_id';
use SoftDeletes;
protected $softDelete = true;
//protected $fillable = ['fl_tax_type' , 'fl_tax_name' , 'fl_charge_type' , 'fl_charge_rate'];
protected $guarded = [];
protected $dates = ['deleted_at'];
}
TaxController.php
<?php
namespace App\Http\Controllers;
use App\Models\Tax;
use Illuminate\Http\Request;
use Validator;
class TaxController extends Controller
{
public function index()
{
$tax = Tax::all();
return $tax;
}
You need to remove the protected $softDelete = true; only leave the use SoftDeletes; will be OK.
With the current information provided, there is no reason that Case 1 should fail. Soft deletes work with the all() method, and I don't see any other issues in the currently provided code that would change that. I will update this answer if more code is provided that reveals the issue.
Case 2 "works" because you're actually calling where() on the Collection of all your Tax records. Tax::all() queries the database and builds a Collection of all the results, and then you're using where() to filter out the results with a null deleted_at field. This is highly inefficient.
Case 3 fails because your select list doesn't contain the deleted_at field. So, when you call where() on the Collection to only see the records where delete_at is null, all records will match since deleted_at doesn't exist. This is still calling where() on the Collection, not adding a where clause to the query, so it is inefficient.
Case 4 "works" again because you added the deleted_at field back in, so it will be in the Collection results, and the filtering can filter out the records where deleted_at is not null. But again, this is filtering the Collection of all your Tax records PHP side, not adding a where condition to your SQL query.
You should try this:
Change your Tax model and try:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
class Tax extends BaseModel
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $table = 'tr_fl_tax_charges';
protected $guarded = ['fl_tax_id','_token'];
}
Related
I want to join three tables. Here is the DB model in server:
lecturers
id - integer (PK)
......
examination
id - integer (PK)
.....
exam_supervision
lecturer_id - integer (FK)
exam_id- integer (FK)
Model relation as I implemented in laravel.
```
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Examsupervision extends Model {
public $timestamps = false;
protected $table = 'exam_supervision';
protected $fillable = ['lecturer_id', 'exam_id'];
}
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Examination extends Model {
public $timestamps = false;
protected $table = 'examination';
protected $fillable = ['name', 'module_id', 'startdate', 'enddate', 'duration', 'type', 'code', 'status'];
}
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Lecturers extends Model {
public $timestamps = false;
protected $table = 'lecturers';
protected $fillable = ['user_id', 'address', 'phone'];
}
```
lecturers, examinations and exam_supervision which is M:M. What I want is find all the examinations of a lecturer.
My code
public function lecturerViewExaminations($id)
{
what code to get all exam for a lecturer..say ID 129
}
Returning me empty set. WHat am I doing wrong? It is easy in SQL syntax but in laravel I am finding it very confusing
What i understand from your question is:
You have one model (Examsupervision) and want the relations examinations and lectures
You can use Eloquent: Relationships
First create a model. In this case your model name would be something like Examsupervision.
In your model(Examsupervision) you can define your relations. In this case examinations and lextures
Create for every relation a new model. So you will have 3 models (Examsupervision, Examinations, Lectures).
Now in your model Examsupervision create a new relation function.
public function lectures()
{
return $this->hasMany('App\Lectures');
}
public function examinations(){
return $this->hasMany('App\Examinations');
}
In your database table "lectures" and "examinations" create a new key with the name examsupervision_id. This key will be the id of the Examsupervision row.
Now in your code when you want the get all the lectures of a given Examsupervision you can do this.
$examsupervision = Examsupervision::find($id); //$id = the Examsupervision you want to retrieve
$lectures = $examsupervision->lectures; //This will return all the lectures connected to examsupervision
And for examinations you can do the same with:
$examsupervision = Examsupervision::find($id); //$id = the Examsupervision you want to retrieve
$examinations = $examsupervision->examinations;
Hope this helps
You are missing ->get() after the last where.
$examinations= Examsupervision::with('lecturers', 'examinations')->where('lecturer_id', 'id')->where('exam_id', 'id')->get();
Model::with() is for relation, Use just ->get()
$examinations=Examsupervision::with('lecturers', 'examinations')->get();
You already have relation for lecturers and examinations.
If not worked, share Model Examsupervision
I am new to Laravel and am struggling with this:
Database - MSSQL existing DB schema cannot be modified as other software depends on it. (not sure if this is a problem or not)
Model/Table setup:
INFO_ALL Table - ID is primary key
PERSON Table - ID is foriegn key
ID's are hex values and I notice eloquent removes the 0x from the start of the value and am not sure if this is causing the relationship to fail or not. example: in the DB I see 0x123456789 in my returned eloquent data I see 123456789
Person Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Person extends Model
{
protected $table = 'PERSON';
protected $primaryKey = 'ID';
public $incrementing = false;
public $timestamps = false;
public function info_all(){
return $this->belongsTo(Info_All::class, 'ID', 'ID');
}
}
Info Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Info_All extends Model
{
protected $table = 'INFO_ALL';
protected $primaryKey = 'ID';
public $incrementing = false;
public $timestamps = false;
public function person(){
return $this->hasOne(Person::class, 'ID', 'ID');
}
}
How I am testing the relationship:
php artisan tinker
$person = App\Person::first();
$person->info;
NULL
php artisan tinker
$info= App\Info::first();
$info->person;
NULL
I know this relationship exists in the DB and I can manuualy get them together with a query but the relationship feature of this framework would really be nice to get figured out.
Beign new to Laravel there are a few things I am unsure about, like if the third argument in the realationship is neccesary since I am declaring the $primaryKey. I declared the $primarykey in the first model because I assummed it is case sensative and my table has ID not id. That being said, I have been stuck on this for a couple days and feel like I have tested everything in every different combination.
Any help is appreciated.
Your relation is defined incorrectly. Try by adding following relation:
Person Model
public function info()
{
return $this->hasOne(Info_All::class, 'ID', 'ID');
}
Info_All model
public function person()
{
return $this->belongsTo(Person::class, 'ID', 'ID');
}
Then try it out in tinker:
$person = App\Person::first();
$person->info;
I am not sure but if eloquent removes the 0x from the start of the value then it can also cause the problem.
Try by removing 0x from your tables.
I'm using laravel and I have a many to many relation between products and orders. There is a pivot table called order-product which has additional information that is updated from time to time. I would like to update the 'updated_at' feild in the order table when the corresponding row in the pivot table is updated or for example if a new product is added.
Is that possible?
The relation between a products and an order is belongsToMany()
Edit: here is some of the code
class Order extends Model
{
protected $table = 'order';
protected $dates = ['updated_at'];
public function products()
{
return $this->belongsToMany(Product::class, 'order_product');
}
}
When I want to remove products its by calling
$order->products()->detach()
So where do I put the $touches array thats mentioned in the laravel docs here
I've tried adding it to the product model but its not working.
You can use the Touching Parent Timestamps, here is an example (from laravel docs).
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* All of the relationships to be touched.
*
* #var array
*/
protected $touches = ['post'];
/**
* Get the post that the comment belongs to.
*/
public function post()
{
return $this->belongsTo('App\Post');
}
}
Normally, I'm dealing with queries I have a two models and I only need to select one model with a whereHas query, which is a greedy condition as it selects as many matches as possible.
Here are my two models:
class Part extends Eloquent {
protected $table = 'parts';
protected $primaryKey = 'part_id';
public function partFlights() {
return $this->hasMany('PartFlights');
}
}
and
class PartFlight extends Eloquent {
protected $table = 'part_flights_pivot';
protected $primaryKey = 'part_flight_id';
public function part() {
return $this->belongsTo('Spacecraft');
}
}
As you can see, there's a 1:m relationship between Part and PartFlight.
What I want is a non-greedy match to select all Part's where all the PartFlight's have the attribute landed set to true. How can I achieve this?
Instead of trying to find out if all are true I suggest you check if none are false ;)
$parts = Part::whereDoesntHave('partFlights', function($q){
$q->where('landed', false);
})->get();
in our project we must be use soft delete for each posts. in laravel document i think we can only use this feature for tables.
can we use that for posts on table such as
$id = Contents::find($id);
$id->softDeletes();
Updated Version (Version 5.0 & Later):
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model {
use SoftDeletes;
protected $table = 'posts';
// ...
}
When soft deleting a model, it is not actually removed from your
database. Instead, a deleted_at timestamp is set on the record. To
enable soft deletes for a model, specify the softDelete property on
the model (Documentation).
For (Version 4.2):
use Illuminate\Database\Eloquent\SoftDeletingTrait; // <-- This is required
class Post extends Eloquent {
use SoftDeletingTrait;
protected $table = 'posts';
// ...
}
Prior to Version 4.2 (But not 4.2 & Later)
For example (Using a posts table and Post model):
class Post extends Eloquent {
protected $table = 'posts';
protected $softDelete = true;
// ...
}
To add a deleted_at column to your table, you may use the softDeletes
method from a migration:
For example (Migration class' up method for posts table) :
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function(Blueprint $table)
{
$table->increments('id');
// more fields
$table->softDeletes(); // <-- This will add a deleted_at field
$table->timeStamps();
});
}
Now, when you call the delete method on the model, the deleted_at column will be set to the current timestamp. When querying a model that uses soft deletes, the "deleted" models will not be included in query results. To soft delete a model you may use:
$model = Contents::find( $id );
$model->delete();
Deleted (soft) models are identified by the timestamp and if deleted_at field is NULL then it's not deleted and using the restore method actually makes the deleted_at field NULL. To permanently delete a model you may use forceDelete method.
You actually do the normal delete. But on the model you specify that its a softdelete model.
So on your model add the code:
class Contents extends Eloquent {
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
}
Then on your code do the normal delete like:
$id = Contents::find( $id );
$id ->delete();
Also make sure you have the deleted_at column on your table.
Or just see the docs: http://laravel.com/docs/eloquent#soft-deleting
I just did this with Laravel 8 and it worked. It's basically what #The alpha said, but trying to wrap everything quicker. Follow this steps.
In the migration file add:
$table->softDeletes();
In the model:
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes;
...
];
}
In the controller:
$user->delete();
Bonus: if you need to restore the deleted user
User::withTrashed()->find($id);->restore();
Just an update for Laravel 5:
In Laravel 4.2:
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Post extends Eloquent {
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
}
becomes in Laravel 5:
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model {
use SoftDeletes;
protected $dates = ['deleted_at'];
In Laravel 5.5 Soft Deleted works ( for me ).
Data Base
deleted_at Field, default NULL value
Model
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model {
use SoftDeletes;
}
Controller
public function destroy($id)
{
User::find($id)->delete();
}
In the Latest version of Laravel i.e above Laravel 5.0. It is quite simple to perform this task.
In Model, inside the class just write 'use SoftDeletes'. Example
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes;
}
And In Controller, you can do deletion. Example
User::where('email', 'youremail#example.com')->delete();
or
User::where('email', 'youremail#example.com')->softDeletes();
Make sure that you must have 'deleted_at' column in the users Table.
Here is the details from laravel.com
http://laravel.com/docs/eloquent#soft-deleting
When soft deleting a model, it is not actually removed from your database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, specify the softDelete property on the model:
class User extends Eloquent {
protected $softDelete = true;
}
To add a deleted_at column to your table, you may use the softDeletes method from a migration:
$table->softDeletes();
Now, when you call the delete method on the model, the deleted_at column will be set to the current timestamp. When querying a model that uses soft deletes, the "deleted" models will not be included in query results.