Laravel 5: How to run a RAW MySQL statement? - php

So I have been moving from framework to framework and one feature that I liked about CodeIgniter over Laravel was that it supplys Raw statements.
I did some research on Laravel and the statements that they can supply and I found the DB::raw($sql) statement.
I tried initially to do the statement like so:
$query = DB::raw("SELECT * FROM users WHERE username = 'admin');
foreach ($query as $q) {
$id = $q['id'];
}
but that didnt manage to work, so I did some more research looking at stack overflow questions and I managed to find the structure was a bit different, so I tried:
$query = DB::select(DB::raw("SELECT * FROM users WHERE username = 'admin');
then used the same foreach loop as I did in the first part to try to loop the data.
If this is the wrong way of using this method please let me know, also, I'm not planning on keeping this method for using raw statements and getting user data, I just am trying to know that is it able to be used.

use get() function :
DB::table('users')->select('*')->where('username', '=', 'admin')->get();

Related

DB::select failing in Laravel 5.2

I have a Laravel 5.2.45 application, also, I have a complex query to do, so I tried to consult it using:
DB::select("the query");
I read that this should work, but it's not the case, so just testing I simplified the query to: "Select * from aTable" but it also doesn't give any result, it takes a long long timeloading the webpage and then just doesnt show anything. I'm using this exactly: dd(DB::select("SELECT * FROM myTable AS mt"))
So, I'm wondering what is exaclty happening, it's still a valid function in Laravel 5.2? it's a really simple query and am not sure in what is failing. Thanks in advance!
I think you are trying to execute raw query. If you execute raw query in laravel please try this way:
$tableData = DB::select( DB::raw("SELECT * FROM table WHERE id = 100 ") );
dd($tableData);
You can set custom function also for printing data in your helper function like
function pr($var){
echo "<pre>";
print_r($var);
echo "</pre>";
}
than you can call pr($tableData);
I think this should work for you. Thank You :)
It's strange but you can check your Query Log to find problem
$users = DB::select('SELECT * FROM myTable AS mt');
print_r(DB::enableQueryLog());
How to enable query log
https://github.com/laravel/framework/commit/e0abfe5c49d225567cb4dfd56df9ef05cc297448
Try this:
$users = DB::table('myTable')->get();

Controller Variable not Showing up in Query Builder Laravel

I am encountering a strange issue in Laravel.
The below is an index function in one of my controllers.
public function index($merchant_url_text)
{
//
$deals = DB::table('tbl_deal')
-> join ('tbl_merchant', 'tbl_deal.merchant_id', '=', 'tbl_merchant.merchant_id')
-> where ('merchant_url_text', $merchant_url_text) -> toSql();
//return $merchant_url_text.$deal_id;
dd($deals);
//return $merchant_url_text;
}
As you can see I am passing merchant_url_text from route.
Route::get('/testroute/{merchant_url_text}', ['uses' =>'dealsVisibleController#index']);
When I am trying to debug the query by printing it, I am getting
"select * from `tbl_deal` inner join `tbl_merchant` on `tbl_deal`.`merchant_id` = `tbl_merchant`.`merchant_id` where `merchant_url_text` = ?"
This means that the query builder is not reading the $merchant_url_text variable. However, when I return just that variable, it is being printed.
Just can't figure out why the query builder is not able to include the $merchant_url_text variable in the query when it is available in the index function.
Any suggestions.
I am pretty sure that your code is correct. The SQL output function toSql() does not show the values of variables and only prints out a ? for security reasons.
You may access all your queries by using
$queries = DB::getQueryLog();
It is also printing the query parameters as array.
To get the last query:
dd(end($queries));
To disable the log:
DB::connection()->disableQueryLog();
See the docs for further information.

how to convert this SQL statement for FluentPDO code

I made this SQL statement to use in a project i'm working on and i have used FluentPDO before but it has been a while and i have never used a subquery in it before, so was wondering if anyone out there knows a good way to do this, i know you can do a JOIN but i am not really familiar with that method and never seen it used before so i don't know enough to make it work, i'm trying to brush up on it so i can do this myself.
SELECT *
FROM users
WHERE username = 'admin'
AND password = 'testing'
AND company_id IN (SELECT company_id
FROM company
WHERE subdomain = 'testing');
$result = $db->from('users')
->innerJoin('company ON users.company_id = company.company_id')
->where('username', 'admin')
->where('password', 'testing')
->where('subdomain', 'localhost')
->fetch();
I figured out the answer, and wanted to post it for anyone that was wondering the same way i was.

Laravel 4 - User should access only his data in a multi-user database

I hope I described the subject properly. I'm creating a contact management application where each user will have his own contacts within the same contact table. Users must not be able to see each other's contacts.
I started by doing this but there must be a better way:
$contact = Contact::where('user_id', Auth::user()->id)->find($id);
The problem with the line above is that I would like to write it this way:
$contact = Contact::find($id)
Is there a way to have the where clause loaded somehow like filters maybe so that all searches have to match the Auth::user()->id?
As suggested, you can use a query scope. Add this in your Contact model:
public function scopeOfUser($query, $user_id)
{
return $query->where('user_id', '=', $user_id);
}
And then use it like this: $contacts = Contact::ofUser(Auth::user()->id)->get();.
I found the answer I was looking for on laracasts.com. (video: Repositories Simplified)
I solved the problem by creating repositories. For example in my ContactController:
$contact = Contact::where('user_id', Auth::user()->id)->find($id);
is now
$contact = $this->contact->getAll();
The DbRepository file has:
public function getAll() {
return $this->model->where('user_id', Auth::user()->id)->get();
}
There's a lot more to it and you'll need to view the video to set it up. It's a lot more work to set up but it's a lot cleaner and the DbRepository can be used by all my controllers since every table will have a user_id field.

Laravel/Eloquent - Using dynamic properties in a multi-field search form

I have a search form in my Laravel app that searches through a list of properties. My properties table has a Model already, and is connected to another Model/table called details, which contains things like if a certain property has a garden, garage etc, through a one-to-many relationship. When doing index or show stuff this works fine - I can get the details for a property using $property->details.
The search form has a field where the user can search for such details, and this is where I'm struggling. I don't just need to find the detail itself, I need to first see if anything present in the input matches anything in the Details table, then see if the foreign key (called prop_id) matches any of my Property id's, then include those properties in the results. Something like:
$query = Property::where('archived',0);
$query->details->where('text',$keyword);
$results = $query->get();
The reason this won't work is because details isn't a property of $query, but I'm not sure what to use as an alternative as calling Property::where() again would surely reset the whole query. I'm storing it all in a $query variable because all the fields in my form are optional, so I'm building the query based only on the inputs that have values in.
Bit stumped here, so if anyone has already tackled something like this, the tips would be appreciated. Cheers!
Use whereHas:
$query = Property::where('archived', 0)->whereHas('details', function ($q) use ($keyword)
{
$q->where('text', $keyword);
});
$results = $query->get();
You may try something like this:
$query = Property::where('archived', 0);
if(isset($keyword)) {
$query->whereHas('details', function ($q) use ($keyword) {
$q->where('text', $keyword);
});
}
$results = $query->get();

Categories