How to echo the last query after eloquent model in laravel 7? - laravel

I am deleting an item like this. The delete method is excuting well but I can't echo the last executed query.
public function deleteItems(Request $request){
$query=null;
switch($request->category){
case('categorylist'):
$category = category::find($request->id);
$query=$category->delete()->toSql();
break;
default:
}
echo json_encode(array('status'=>2, 'msg'=>'Successfully deleted', 'query'=>$query->toSql()));
}

The toSql() method works only on instances of Illuminate\Database\Query\Builder ( query builder as it is usually called ). Methods like where(), orderBy() etc return an instance of query builder, hence toSql() works on them. The delete() method does not return an instance of query builder ( I think it returns Boolean or the id it deleted. Can't remember ). So the toSql() method won't work.
If you just want to get the last executed query, then you could use DB::getQueryLog(). For example
DB::enableQueryLog();
$category->delete();
$queryLog = DB::getQueryLog();
// Now $queryLog will contain all the SQL queries which were executed after the DB::enableQueryLog()
$last = end($queryLog);
$query = $last['query'];
$bindings = $last['bindings'];

Related

I would like to check a SQL query of Laravel builder

Method Illuminate\Database\Eloquent\Collection::toSql does not exist.
occured when I tried this
My laravel version 6.20
$query = Car::where($criteria)
->get(['id'])->shuffle();
$sql = $query->toSql();
Log::info($sql);
When you execute the query using get() it will return an instance of Illuminate\Database\Eloquent\Collection class. And there's no method named toSql() on the Collection class.
If you want to inspect the sql you should
$query = Car::where($criteria)->select('id');
//Here $query is an instance of Illuminate\Database\Eloquent\Builder
//And it has a method named toSql
$sql = $query->toSql();
Log::info($sql);
$query->get()->shuffle();
You could use dd or dump methods for debugging purposes.
Source: https://laravel.com/docs/6.x/queries#debugging

Laravel eloquent call realtionship based on a boolean parameter

I'm trying to make a method to retrieve model with a relationship I'd like to be able to fetch the relation based on a boolean parameter
for example, I can do it using the if condition like the following
if($load == true){
$users = User::with('login')->all()->paginate();
}else{
$users = User::all()->paginate();
}
I'm wondering if there's a way to do it without the if condition on the fly
You can use the when() method on the query builder. Note that you don't need to use the all() method when you want to use a paginator.
User::query()
->when($load, fn($query) => $query->with('login'))
->paginate();
you can use when method:
$users = User::when($load, function ($query) {
return $query->with('login');
})->paginate(10);
The when method only executes the given closure when the first argument is true. If the first argument is false, the closure will not be executed

Laravel Method paginate does not exist trying controller

$article = Article::all()->sortBy("order")->paginate(3);
return view('nieuws' , compact('article'));
wont work this is the error I get back:
Method Illuminate\Database\Eloquent\Collection::paginate does not exist.
When you're using all() you get all the rows from the table and get a collection. You can only invoke "paginate" on a Query, not on a Collection. :
$article = Article::orderBy("order")->paginate(3);
There is no sortBy() method on the query builder, it should be orderBy. You can only invoke "sortBy" on a Collection, not on a Query.

Codeigniter: does $this->db->last_query(); execute a query?

Does query execution happen at the get_where() clause of the following codeigniter active record statement?
$this->db->select('*');
$q = $this->db->get_where('Contacts', array('id' => $contact_id));
$sql = $this->db->last_query();
Or does it happens once you call the result_array()?
And is $this->db->last_query(); a reliable way in getting the query string.
The query execution happens on all get methods like
$this->db->get('table_name');
$this->db->get_where('table_name',$array);
While last_query contains the last query which was run
$this->db->last_query();
If you want to get query string without execution you will have to do this.
Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now you can write query and get it in a variable
$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();
Now reset query so if you want to write another query the object will be cleared.
$this->db->_reset_select();
And the thing is done. Cheers!!!
Note : While using this way you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
Take a look at this example
For me save_queries option was turned off so,
$this->db->save_queries = TRUE; //Turn ON save_queries for temporary use.
$str = $this->db->last_query();
echo $str;
Ref: Can't get result from $this->db->last_query(); codeigniter
For Me It Works Perfectly: Source Disclosure : This Source website Belongs to me , i am also sharing solutions on my website ...
public function index()
{
$db = \Config\Database::connect();
$heroesCount = $db->table('products')->countAll();
echo $db->getLastQuery();
exit;
}

Active Record and queries with CodeIgniter

I am using codeigniter for my application and i am a bit confused, I wrote some queries like that:
public function checkemail($email) {
$this->db->select('email')->from('user')->where('email', $email);
}
But in the manual of codeigniter ( http://codeigniter.com/user_guide/database/active_record.html ) they talk about $this->db->get();
Should I add it after the $this->db->select query?
My function works fine...
When should I use get() ?
Thanks you!
Yes, you'll need to run get() after the other methods. select(), from() and where() add their respective statements to the query, and get() actually runs the query and returns the result as an object.
In this case, you could just add it on to the end of the chain.
public function checkemail($email) {
$this->db
->select('email')
->from('user')
->where('email', $email)
->get();
}
If you want to work with the result afterwards, make sure that you are assigning it to a variable.
$user = $this->db
->select('email')
->from('user')
->where('email', $email)
->get();
If you use get("table_name") then you don't need to use from("table_name"). It's just an alternative syntax it seems.
From the user guide, all the way at the bottom it says: As shown earlier, the FROM portion of your query can be specified in the $this->db->get() function, so use whichever method you prefer.

Resources