LIKE doesn't return results - laravel

I am trying to find "sam" inside FullName in the table users with this eloquent operation:
$user = User::where('id', '=', $input)->orWhere('fullName', 'LIKE', "%$input%")->find(10);
finding through id works as expected but the Where with LIKE isn't returning any results.
(if $input is 1 the first where returns a result but if $input is sam the second where doesn't return anything)
In the database fullName has the value "Sam Pettersson".
Anything I am doing wrong?

For some reason laravel doesn't want find() and like queries in the same query so using this instead worked:
$user = User::where('id', '=', $input)->orWhere('fullName', 'LIKE', "%$input%")->take(10)->get();

$user = User::where(function($query) use($input)
{
$query->where('id', '=', $input)
->orWhere('fullName','LIKE', '%'.$input.'%');
})->get();
This worked for me. Hope this work for you.

Related

use of orWhere() in Eloquent

I have a eloquent query that I am running twice, but feel can be run once.
I'd want to return the values of the first where statement if exists otherwise check the second where statement which is the default in the query.
This is what I am currently doing:
$details = Telco::select('telcos.id AS telco_id', 'telcos.name AS telco_name')
->leftJoin('telco_prefixs', 'telco_prefixs.telco_id', '=', 'telcos.id')
->where('telco_prefixs.prefix', '=', $phone_number) // check if ndc exists
->first();
if ($details){
return $details;
}
return Telco::select('telcos.id AS telco_id', 'telcos.name AS telco_name')
->leftJoin('telco_prefixs', 'telco_prefixs.telco_id', '=', 'telcos.id')
->where('telcos.name', '=', 'Default') //default channel
->first();
I have a feeling this can be combined to something like below:
However, this fails as keeps executing the OrWhere clause.
Telco::select('telcos.id AS telco_id', 'telcos.name AS telco_name')
->leftJoin('telco_prefixs', 'telco_prefixs.telco_id', '=', 'telcos.id')
->where('telco_prefixs.prefix', '=', $phone_number) // if ndc exists
->Orwhere('telcos.name', '=', 'Default') //default channel
->first();
Someone help. Thanks
Try to add your where and or where condition as below.
Telco::select('telcos.id AS telco_id', 'telcos.name AS telco_name')
->leftJoin('telco_prefixs', 'telco_prefixs.telco_id', '=', 'telcos.id')
->where(function ($query) use($phone_number) {
$query->where('telco_prefixs.prefix', '=', $phone_number);
$query->Orwhere('telcos.name', '=', 'Default');
})->first();
I you want to use just eloquent a possible solution would be to have something like:
I suppose you have model called Telco and another one calle TelcoPrefix.
//Telco.php
//first we create a has many relationship with your telco_prefixs table.
public function telcoPrefixs(){
return $this->hasMany(TelcoPrefix::class);
}
Once you have that relationship you can use something similar to this code:
Telco::whereHas('telcoPrefixs',function($query, $phone_number){
return $query->where('prefix,'=',$phone_number);
})->select('id','name')->first();
This will compare the relationship and if it exists or has it will return your first record in one query.
Hope it helps at least to give a guide of what you can do.

Laravel 5.5 can't get selected column data using belongsTo

I have 2 models (User & UsersDetails) in relation with Eloquent Laravel.
Model "User" Realation With 'SelDetails'
public function SelDetails {
return $this->belongsTo('App\UsersDetails', 'users_id');
}
I want to get only two column 'created_by_id', 'created_by_name' from SelDetails
UserController
$users = User::with(['SelDetails' => function($query){
$query->select(['created_by_id', 'created_by_name']);
}])
->where('is_active', '=', 0)
->orderBy('id', 'desc')
->get();
I am getting data from User but getting blank in SelDetails
[relations:protected] => Array
(
[SelDetails] =>
)
Please correct me.
guys thanks for your precious response on this issue. i got the solution via following way.
changes in "User" model Relation With 'SelDetails'
public function SelDetails {
#return $this->belongsTo('App\UsersDetails', 'users_id');// the old one
return $this->hasOne('App\UsersDetails', 'users_id');
}
changes in "UserController"
$users = User::with('SelDetails')->where('is_active', '=', 0)->orderBy('id', 'desc')->get();
that's the changes that I have made and got the result
Thanks
I might be wrong but it might be the array in select, try
$query->select('created_by_id', 'created_by_name');
Have you tried something like
$users = App\Book::with('author:id,name')->get(); from the documentation?
In your case it should looks like:
User::with('SelDetails:created_by_id,created_by_name')
->where('is_active', '=', 0)
->orderBy('id', 'desc')
->get();
with() method can take string (or array filled by strings) eg. relationName:column1,column2.

Eloquent User Where Clause with Entrust Library

I'm trying to select all users for a company. But only users who has "admin" role status (Entrust, etc.).
User::where('company_id', Auth::user()->company_id)->hasRole('admin')->get();
The above is throwing an error. Left a bit lost on how to run such a query. Where am I going wrong with this? Very little documentation on Entrust.
You can use plain Eloquent for this. The whereHas method would generate one query:
$users = User::where('company_id', Auth::user()->company_id)
->whereHas('roles', function($query) {
$query->where('name', 'admin');
})->get();
Or, you can just get the roles and then get all of that role's users. This would generate two queries, but ultimately achieve the same thing.
$users = Role::where('name', 'admin')
->first()
->users()
->where('company_id', Auth::user()->company_id)
->get();
Think you need to get all the users having the company_id first
$users = User::where('company_id', Auth::user()->company_id)->get();
Then loop through $users and check hasRole()
foreach ($users as $user) {
if($user->hasRole('admin')){
//user is admin
}
}
UPDATE
This might be a dirty solution but you can try to do a manual query
$admin = DB::table('role_user')
->join('users', 'users.id', '=', 'role_user.user_id')
->join('roles', 'roles.id', '=', 'role_user.role_id')
->where('roles.name', 'admin')->get();

Why does this return only one result?

I have the following query. The query should be returning all five rows that I have where user_id = 1, but it's only returning the first result. Why?
$servers = DB::table('posts as p')
->select('p.id', 'p.content', DB::raw('COUNT(i.id) as num_results'))
->leftJoin('images as i', 'i.post_id', '=', 'p.id')
->where('p.user_id', Auth::id())
->get();
Thank you.
public function index(User $user)
{
$users = $user
->where('rol','2')//for normal user
->leftjoin('cityes', 'cityes.id', '=', 'users.cityes_id')
->select('users.id', 'users.name','cityes.name as city')
->get();
}
this code is work for me try this way

Laravel eloquent and relationship

I have a code:
$response = $this->posts
->where('author_id', '=', 1)
->with(array('postComments' => function($query) {
$query->where('comment_type', '=', 1);
}))
->orderBy('created_at', 'DESC')
->limit($itemno)
->get();
And when I logged this query with:
$queries = \DB::getQueryLog();
$last_query = end($queries);
\Log::info($last_query);
In log file I see follow:
"select * from `post_comments` where `post_comments`.`post_id` in (?, ?, ?, ?) and `comment_type` <> ?"
Why is the question mark for comment_type in the query?
Update #1:
I replaced current code with following and I get what I want. But I'm not sure it is OK. Maybe exists many better, nicer solution.
$response = $this->posts
->where('author_id', '=', 1)
->join('post_comments', 'post_comments.post_id', '=', 'posts.id')
->where('comment_type', '=', 1)
->orderBy('created_at', 'DESC')
->limit($itemno)
->get();
Behind the scene the PDO is being used and it's the way that PDO does as a prepared query, for example check this:
$title = 'Laravel%';
$author = 'John%';
$sql = "SELECT * FROM books WHERE title like ? AND author like ? ";
$q = $conn->prepare($sql);
$q->execute(array($title,$author));
In the run time during the execution of the query by execute() the ? marks will be replaced with value passed execute(array(...)). Laravel/Eloquent uses PDO and it's normal behavior in PDO (PHP Data Objects). There is another way that used in PDO, which is named parameter/placeholder like :totle is used instead of ?. Read more about it in the given link, it's another topic. Also check this answer.
Update: On the run time the ? marks will be replaced with value you supplied, so ? will be replaced with 1. Also this query is the relational query, the second part after the first query has done loading the ids from the posts table. To see all the query logs, try this instead:
$queries = \DB::getQueryLog();
dd($queries);
You may check the last two queries to debug the queries for the following call:
$response = $this->posts
->where('author_id', '=', 1)
->with(array('postComments' => function($query) {
$query->where('comment_type', '=', 1);
}))
->orderBy('created_at', 'DESC')
->limit($itemno)
->get();
Update after clarification:
You may use something like this if you have setup relation in your Posts model:
// $this->posts->with(...) is similar to Posts::with(...)
// if you are calling it directly without repository class
$this->posts->with(array('comments' =. function($q) {
$q->where('comment_type', 1);
}))
->orderBy('created_at', 'DESC')->limit($itemno)->get();
To make it working you need to declare the relationship in your Posts (Try to use singular name Post if possible) model:
public function comments()
{
return $this->hasmany('Comment');
}
Your Comment model should be like this:
class Comment extends Eloquent {
protected $table = 'post_comments';
}

Resources