Laravel Doesn't Use the Right Table - php

Laravel picks the wrong table, the users table. I have switched the table in config/auth to the correct one but for some reason, Laravel still uses the default users table.
Code
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class UserLoginController extends Controller
{
protected $table = 'pupil';
public function showLoginForm()
{
return view('home');
}
public function login(Request $request)
{
$this->validate($request, [
'user' => 'required',
'password' => 'required|min:3'
]);
$user = User::where('accountName', $request->user)
->where('password', $request->password)
->first();
if ($user) {
Auth::login($user);
return redirect()->route('neue_anmeldung');
}
return redirect()->back()->withInput('email');
}
}
I get the following error message.
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'database1.users' doesn't exist (SQL: select * from users where
accountName = 6001 and password = password limit 1)

Your User model is configured to use the users table. You have defined the table in your controller which is wrong. You need to define the property protected $table = 'pupil'; in your App\User.php

By default eloquent Will assumes the tables as follows
For Example
If Your Model name is
User Then it will search for users table in database
AdminUser Then it will search for admin_users table in database
To Change the default tablename assumed by eloquent
Open Your Current Model
Not Your Controller
and protected $table = 'yourTableNAme';
Hope it helps

Related

Laravel query issue whene user is deleted

Here is my database table.
to_user_id is deleted in the users table that time total_like not should be 1
Here is my code
$user_id = 585;
$list = new self;
$list = $list->where('users.id', $user_id);
$list = $list->leftJoin('user_like_dislikes as total_like', function ($join) use ($user) {
$join->on('users.id', '=', 'total_like.to_user_id')
->where('total_like.like', 1);
});
$list = $list->select('users.*', \DB::raw('count(total_like.like) as total_like')
$list = $list->first();
Here are my user_like_dislikes data table
user_id
to_user_id
like
585
590
1
Here is my user table
id
deleted_at
590
Null
I above code to_user_id is not deleted in the user table so the output is total like is 1
But when I delete to_user_id in the users table that time output is total like 1 getting. this is wrong.
So, I want where I delete to_user_id in the users table that time total like should be 0
better way use relation to get solve this problem.
try bellow code :
in user model :
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
class User extends Model
{
protected $table = 'users';
public function likes(): HasMany
{
return $this->hasMany(Like::class, 'to_user_id', 'id');
}
}
the Like model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Like extends Model
{
protected $table = 'user_like_dislikes';
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
}
And Finally your query is:
$data = \App\Models\User::query()
->where('id',585)
->withCount('likes as likes_count') // for getting count of rows
->withSum('likes as likes_sum','like') // for getting sum of like column
->first();
$data->likes_count and $data->likes_sum your want value
and for handle soft delete you should use bellow tarit in user model
use \Illuminate\Database\Eloquent\SoftDeletes;

SQLSTATE[HY000]: General error: 1364 Field 'contactId' doesn't have a default value

On my model (Customer) I have one required parameter: $contactId.
On executing Customer::create(['contactId' => $contactId]) I receive the following error:
"message": "SQLSTATE[HY000]: General error: 1364 Field 'contactId' doesn't have a default value (SQL: insert into customers (updated_at, created_at) values (2019-12-10 12:33:46, 2019-12-10 12:33:46))"
The contactId field is nowhere to be found on in the insert statement. The value of contactId is set to 4, which corresponds to the correct value in the database through a FK.
The migration for the Customer table:
`Schema::create('customers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));
$table->bigInteger('contactId')->unsigned();
$table->foreign('contactId', 'FK_customer_contactId_contact_id')
->references('id')
->on('contacts');
});`
What's preventing Eloquent from creating the correct insert statement here? I've triple checked the spelling of contactId throughout the flow and in the database.
When I manually insert a row into customers, I have no issues retrieving the data and the contact-relation.
Thanks for your time!
Make contactId $fillable in Customer model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
protected $fillable = ['contactId'];
}
If you use create method to save data in to database so you must have to write this fillable property in your model
<?php
class Customer extends Model
{
protected $fillable = ['contactId'];
}
Make contactId $fillable in model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
protected $fillable = ['contactId'];
}
or
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
protected $guarded = [];
}

how to create a query with multiple tables in laravel

i want to create a query with multiple tables
the query that i need is:
SELECT orders.user_id, orderitem.product_id, orderitem.orderItem_quantity, product.product_price, product.product_imgPath,product.product_name
FROM orderitem, orders, product, users
WHERE orders.user_id = '$_Session[user_id]'
AND orderitem.product_id = product.product_id
AND orderitem.order_id = orders.order_id
AND orders.order_status = 1
and i try these codes:
1:
$cartProducts = DB::table('orderitem')
->join('product','product.product_id','=','orderitem.product_id')
->join('orders','orders.order_id','=','orderitem.order_id')
->where('orders.order_status','=','Waiting')
->where('orders.user_id','=',$userId)
->select('orderitem.*','orders.*','product.*','users.*')
->get();
The error that i get is:
SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'users'
2:
$cartProducts = DB::table('orderitem','orders','products','users')
->select('orderitem.*','orders.*','products.*','users.*')
->where('orders.user_id','=',$userId)
->where('orderitem.product_id','=','product.product_id')
->where('orderitem.order_id','=','orders_id')
->where('order_status','=','Waiting')
->get();
The error that i get is:
SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'orders'
And i know that i can't use multiple parameter for table function
Use laravel relationships https://laravel.com/docs/5.5/eloquent-relationships#one-to-many
First, in your User model do:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function images()
{
return $this->hasMany('App\Images'); //make sure your images table has user_id column
}
}
And then in your Image table model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
Now in your controller:
$data = App\Post::user(1)->with('images');
return view('view_name', ["data" => $data]);
Your view:
#foreach($data->images as $image)
<img src="{{ $image->url }}">
#endforeach

How to use orderby on element that was joined with Laravel Eloquent method WITH

The problem is that the query can't find the specific_method(specific_method, specific_model,SpecificModel,specificMethod etc...), that should been joined with the method WITH from Laravel Eloquent. Any ideas how to solve it?
My code:
//SpecificModel
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class SpecificModel extends Model {
protected $guard_name = 'web';
protected $table = 'SpecificTable';
protected $guarded = ['id'];
public function specificMethod(){
return $this->belongsTo('App\Models\AnotherModel','AnotherModel_id');
}
}
//AnotherModel
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class AnotherModel extends Model {
protected $guard_name = 'web';
protected $table = 'AnotherTable';
protected $guarded = ['id'];
}
//Query method
$model = app('App\Models\SpecificModel');
$query = $model::with('specificMethod:id,title');
$query = $query->orderBy('specific_method.title','desc');
return $query->get();
//Error
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'"specific_method.title"' in 'order clause' (SQL: select * from
`SpecificModel` where `SpecificModel`.`deleted_at` is null order by
`specific_method`.`title` desc)
This happens because the belongsTo relationship does not execute a join query as you expect it to (as you can see from the error you get). It executes another query to get the related model(s). As such you will not be able to order the original model by related models columns.
Basically, 2 queries happen:
Fetch the original model with SELECT * from originalModel ...*
Fetch the related models with SELECT * from relatedModel where in id (originalModelForeignKeys)
Then Laravel does some magic and attaches the models from the 2nd query to the correct models from the first query.
You will need to perform an actual join to be able to order the way you want it to.

Error while trying to get max number from SQL database using eloquent

I have a database running with username, password and user_id as primary key
and I'm trying to get the highest number out of the user_id column using eloquent.
This is my current error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.id' in 'where clause' (SQL: select * from users where users.id = 2 limit 1)
This is what my model looks like:
users.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use DB;
use Eloquent;
class users extends Eloquent
{
public static function register()
{
$user_id = users::find(DB::table('users')->max('user_id'));
return $user_id;
}
}
Usually, Laravel considers the primary key name is id. You must declare your primary key name if it's not id. So, add this in your user class:
protected $primaryKey = 'user_id';
Here is how the whole class should look:
class users extends Eloquent
{
protected $primaryKey = 'user_id';
public static function register()
{
$user_id = users::find(DB::table('users')->max('user_id'));
return $user_id;
}
}
Get the highest user like this
$user = users::orderBy('user_id', 'desc')->first();

Categories