Laravel - use multiple value in where DB query - laravel

in my posts table have extra_category column with saved mutiple value(json) same ["12","15","23"] now I want use this value in DB query for get category name for each value .
my Controller:
$excatname = DB::table('categories')
->where('id', '=', $post->extra_category)->get();
view()->share('excatname', $excatname);
and my view:
#foreach($excatname as $excatnamez)
{{ $excatnamez->name }}
#endforeach
but get error:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens (SQL: select * from `categories` where `id` = 12)
Note: when extra_categoy have single value for ex : 15 worked as well.
cast is defined on the model
protected $casts = ['extra_category' => 'array',]

Related

SQLSTATE[42S22]: Column not found: 1054 Unknown column '' in 'order clause'

I'm trying to make pagination after sorting in my Laravel project , so I did this method, it sorts my data but when I want to see next paginate table it shows me this error
SQLSTATE[42S22]: Column not found: 1054 Unknown column '' in 'order clause'
SELECT * FROM `customers` ORDER BY `` DESC limit 3 OFFSET 3
My method
public function Sortfilter(Request $request)
{
$active = Customer::where('active','=','1')->count();
$inactive = Customer::where('active','=','0')->count();
$customer = Customer::query();
$customer = Customer::orderBy($request->filter,'desc')->paginate(3);
return view('customers.index', compact('customer','inactive','active'));
}
is there a method to save the $request->filter data when I click on next button
EDIT
when i sort my data the URL change like that : http://127.0.0.1:8000/sortCustomer?filter=phone&_token=9xw0q9MKa5ABZc4CwkLaPqf5ko4BhJ4ZaEk0VKYY
and when i click to the pagination button the URL be like that :
http://127.0.0.1:8000/sortCustomer?page=2
The problem is sometimes your $request->filter is empty, so adding a default value when it's empty fixes that.
public function Sortfilter(Request $request)
{
$active = Customer::where('active','=','1')->count();
$inactive = Customer::where('active','=','0')->count();
$customer = Customer::query();
$filter = $request->filter ?: 'created_at';
$customer = Customer::orderBy($filter,'desc')->paginate(3)>appends(['filter' => $request->filter]);
return view('customers.index', compact('customer','inactive','active'));
}
I think you are passing '' (null) in the first parameter of orderBy clause.
please confirm that the value in the $request->filter parameter not null and it should be a column name as in the customer table.
In Laravel there is the option to append query string values to pagination links.
Using this your code could look like this:
public function Sortfilter(Request $request)
{
$active = Customer::where('active','=','1')->count();
$inactive = Customer::where('active','=','0')->count();
$customer = Customer::query();
$customer = Customer::orderBy($request->filter,'desc')->paginate(3)->withQueryString();
return view('customers.index', compact('customer','inactive','active'));
}

Eloquent query check if null when data is on another table

I have a table name EmployeeCourses that has a relationship with course_detail table and I have this eloquent query in Laravel:
$result = EmployeeCourses::where([['user_id', '=', '01'],['status','!=', 'Completed'] ])->whereDate('start_date','<=',$current_date)->with('course_details')->get();
Can I check if the course_details is not equal to null and if null or empty than don't include it in the $result?
I think you are looking for whereHas('relation').
$result = EmployeeCourses::where([
['user_id', '=', '01'],
['status','!=', 'Completed']
])->whereDate('start_date','<=',$current_date)
->whereHas('course_details')
->with('course_details')->get();
this method will return 'EmployeeCources' only if it has at least one 'Course Detail' is assigned.

Column not found laravel 5.4

I get the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'books.id' in
'where clause' (SQL: select * from books where books.id =
98745632564 limit 1)
when I pass id value as id. I have column name bookID in my database but in the above error it is comparing books.id = 98745632564. I could not understand where book.id is coming from.
public function showBook($id){
$book = Book::findOrFail($id);
return $book;
}
The code works perfectly fine when I pass id value with the query as follows
public function showBook($id){
$book = Book::where('bookID', $id)->find();
return $book;
}
You should set:
protected $primaryKey = 'bookID';
in your Book model to make:
$book = Book::findOrFail($id);
version work.
Methods find or findOrFail are using primary key and this is by default set to id, so if you have any custom primary key, you should set it in your Eloquent model.

How to update field in table Laravel or create?

I try to update field rate in table by primary key user_id.
So, I need to increment of decrement rate field. If row is not exist I need to create it.
I tried:
$this->point = -1; // Or $this->point = 1;
Rating::updateOrCreate(["user_id", $id], ["rate" => $this->point]);
But it does not work:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * from `rating` where (`0` = user_id and `1` = 5) limit 1)
This is because your passing the column and the value as two separate values.
Change:
["user_id", $id]
to:
["user_id" => $id]
Hope this helps!
Laravel (eloquent) provides a fluent way to update related models.
Assuming the following model structure:
Rating.php
public function user()
{
return $this->belongsTo('App\User');
}
User.php
public function ratings()
{
return $this->hasMany('App\Rating');
}
You can easily update the relation via associate()
$user = User::findOrFail($userId);
$rating = Rating::findOrFail($ratingId);
$rating->user()->associate($user)->save();
Read more about Relationships in Eloquent

Is it possible to define primaryKey on runtime for Laravel / Eloquent?

In Eloquent, I know it's possible to define the table on runtime with $model->setTable().
I tried adding a new item in the constructor like:
$myModel = new \MyModel(array(), 'my_primary_key');
$myModel->setTable('mytable');
with the constructor being:
class MyModel extends Eloquent {
public function __construct($attributes = array(), $primaryKey = 'id') {
parent::__construct($attributes); // Eloquent
$this->primaryKey = $primaryKey;
}
}
That makes my $primaryKey = 'id' like the default.
- This one doesn't work cause it doesn't change the primaryKey to whatever I define in my call the constructor, it just gets the default ('id'). If I don't set a default I get the following error:
Missing argument 3 for MyModel::__construct(), called in
/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 517 and defined
I also tried:
$myModel->setAttribute('primaryKey', 'my_primary_key');
But this one doesn't set the attribute
But nothing works. The default for Laravel is having 'id' as the primaryKey, but in my tables I have things like 'car_id' for table Cars, and so on, so I get errors like:
Column not found: 1054 Unknown column 'id' in 'where clause'
(SQL: select * from `cars` where `id` = 1 limit 1)
I tried to look into the code: https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Model.php#L1415, but it doesn't have a method to set it on runtime.

Resources