Can I use where in eloquent while giving it an object? - php

I'm new to Laravel & Eloquent, I'm coming from Django.
In Django I can create a filter on my results and use an object to filter the results...
I'm trying to figure out if I could do this in Laravel/Eloquent also...
Here's what I'm trying to do....
create_messages_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMessagesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('messages', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('user_id');
$table->string('message');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('messages');
}
}
Message.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Message extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
MessageController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Message;
use Illuminate\Support\Facades\Auth;
class MessageController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$messages = Message::where("user", Auth::user())->get();
dd($messages);
return $messages;
}
}
The problem is that when the controller index() function is routed too... I get an error saying "user" column does not exist... and it doesn't but I assumed the models user() function would take care of that and that I would be able to compare it's returning object with Auth::user().
Am I wrong, or am I just doing it wrong?

In the "where" query, the first parameter must be a column in the database. If you want to make use of a "user" column, I'll suggest you add a user column to your table.
I think the auth:user() is to authenticate the current user.
So laravel eloquent is only alerting you that the "user" column does not exist. I will suggest you create a user column, and see what happens next.

Related

Problem with seeding data in pivot table in Laravel

I have a problem while attempting to seed my pivot table in database in Laravel. I get error
Base table or view not found: 1146 Table 'user_cuisines' doesn't exist
And my table name is actually user_cuisine, so it is like for some reason laravel doesn't show that table. I added in my relationships that user_cuisine is pivot table because of alphabet order. Any help is appreciated. Here is my code.
UserCuisineTableSeeder.php
<?php
use App\UserCuisine;
use App\UserProfile;
use Illuminate\Database\Seeder;
class UserCuisineTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$cuisines = UserCuisine::all();
UserProfile::all()->each(function ($userProfile) use ($cuisines) {
$userProfile->cuisines()->attach(
$cuisines->random(rand(1, 12))->pluck('id')->toArray()
);
});
}
}
DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call(WhitelabelTableSeeder::class);
$this->call(CitiesTableSeeder::class);
$this->call(UserTableSeeder::class);
$this->call(UserProfilePropertiesSeeder::class);
$this->call(UserProfileTableSeeder::class);
$this->call(FieldTableSeeder::class);
$this->call(FieldValueTableSeeder::class);
$this->call(CuisineTableSeeder::class);
$this->call(LiteratureTableSeeder::class);
$this->call(MusicTableSeeder::class);
$this->call(SportTableSeeder::class);
$this->call(TvTableSeeder::class);
$this->call(UserCuisineTableSeeder::class);
$this->call(UserInterestTableSeeder::class);
}
}
UserCuisine.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserCuisine extends Model
{
protected $fillable = [
'name'
];
public function userProfiles()
{
return $this->belongsToMany(UserProfile::class, 'user_cuisine');
}
}
UserProfile.php
<?php
namespace App;
class UserProfile
{
public function user()
{
return $this->belongsTo(User::class);
}
public function cuisines()
{
return $this->belongsToMany(UserCuisine::class, 'user_cuisine');
}
}
user_cuisine_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUserCuisineTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('user_cuisine', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('cuisine_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('user_cuisine');
}
}
cuisine_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCuisineTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('cuisine', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('cuisine');
}
}
Laravel expect the table name to be user_cuisines but you named it user_cuisine without the "s"
You can fix that by changing your migration or adding protected $table = 'user_cuisine'; to your model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserCuisine extends Model
{
protected $table = 'user_cuisine';
}
As naming convention goes, I would recommend changing the table name 👍
Seems user_cuisines table does not exist, You have created cuisine not user_cuisines
Just put below code in UserCuisine model.
protected $table= 'user_cuisine';
I would recommend always use -m flag while creating a model to avoid these types of errors, for example.
php artisan make:model ModelName -m

How to use 'get' method with the where eloquent in laravel

I was trying to get all the elements sharing a common row data
but I keep getting this error I do not know why
Call to a member function get() on null
Here is the code I used, I have imported the App\User and everything but still not getting it and I have a user in my table with that role_id
My controller
<?php
namespace App\Http\Controllers;
use App\Animal;
use App\Clinic;
use App\Role;
use App\Slaughter;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ClinicController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$farms = User::where('role_id', 3);
$user = Auth::user();
$animal = Animal::all();
return view('clinic.index', compact('user', 'animal', 'farms'));
}
My user table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->unsignedBigInteger('address_id')->index();
$table->unsignedInteger('role_id');
$table->string('description')->nullable();
$table->timestamps();
$table->foreign('address_id')->references('id')->on('addresses');
});
}
But I am keep getting that error bellow I do not know the why
use App/User;
$farm = User::where('role_id', 3)->get();
Try below code for getting the record
$farm = User::select(['id','name'])->where('role_id', 3)->get();
In case the User class extends Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model{}
calling
$builder = User::where('role_id', 3);
always returns an object of type Illuminate\Database\Eloquent\Builder, therefore, calling
$user= User::where('role_id', 3)->get();
always returns a collection (which might be empty when there is no user with role_id = 3). Check the type of your User class.
I think there are some missed steps that you didn't take.
The User does not refer to the table name but to the model class name. So first things first you need to create a model.
In order to do that you use the command:
php artisan make:model User
If you want a dedicated Models folder(i always use one) you use
php artisan make:model Models/User
By that time you should have a model created but you need to set it up.
Going inside your User.php file you should have something like this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are NOT mass assignable.
*
* #var array
*/
protected $guarded = [
'created_at', 'updated_at', 'password,
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
//
];
}
Now by including your model at the top of your file you can use your Model class.

SQLSTATE[42S22]: Column not found: 1054 Unknown column in laravel

I'm trying to make a shopping cart with laravel and am having trouble with one of the methods
this is the error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'pedidos__produtos.pedidos_id' in 'where clause' (SQL: select id_produto, sum(total) as Total, count(1) as qtd from pedidos__produtos where pedidos__produtos.pedidos_id = 1 and pedidos__produtos.pedidos_id is not null group by id_produto order by id_produto desc)
I searched the entire code, but I did not refer this field "pedidos_id" anywhere
This error happens when I call "$pedidos[0]->pedido_produtos," in Carrinhocontroller.php
These are the related methods and migrations:
CarrinhoController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Pedidos;
use Illuminate\Support\Facades\Auth;
class CarrinhoController extends Controller
{
function __construct(){
$this->middleware('auth');
}
public function index(){
$pedidos = Pedidos::where([
'id_user' => Auth::id()
])->get();
dd([
$pedidos,
$pedidos[0]->pedido_produtos,
//$pedidos[0]->pedidos_produtos[0]->produto
]);
return view('carrinho.index', compact('pedidos'));
}
}
Pedidos.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Pedidos extends Model
{
public function pedido_produtos(){
return $this->hasMany('App\Pedidos_Produtos')
->select( \DB::raw('id_produto, sum(total) as Total, count(1) as qtd'))
->groupBy('id_produto')
->orderBy('id_produto', 'desc');
}
}
Pedidos_Produtos.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Pedidos_Produtos extends Model
{
public function produto(){
return $this->belongsTo('App\Produtos', 'id_produto', 'id');
}
}
Migration from Pedidos:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePedidosTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('pedidos', function (Blueprint $table) {
$table->increments('id');
$table->integer('id_user')->unsigned();
$table->foreign('id_user')->references('id')->on('users');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('pedidos');
}
}
and from pedidos_produtos
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePedidosProdutosTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('pedidos__produtos', function (Blueprint $table) {
$table->increments('id');
$table->integer('id_pedido')->unsigned();
$table->integer('id_produto')->unsigned();
$table->decimal('total', 6, 2)->default(0);
$table->timestamps();
$table->foreign('id_pedido')->references('id')->on('pedidos');
$table->foreign('id_produto')->references('id')->on('produtos');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('pedidos__produtos');
}
}
Can Anyone help me with that?
It generates automatically if foreignKey attribute is not defined on hasMany method.
it generates field name from classname_id pattern. Also localKey default value is class PK.
public function hasMany($related, $foreignKey = null, $localKey = null)
You can use like this.
return $this->hasMany('App\Pedidos_Produtos','id_pedido')
The problem you are experiencing is probably to do with this line:
return $this->hasMany('App\Pedidos_Produtos')
If you do not explicitly tell Laravel what the IDs are called on each table when defining a hasMany relationship, it will assume that the id is {table_name}_id which is where the pedidos_id is coming from.
Try adding the foreign and local keys to the hasMany, something like this:
return $this->hasMany('App\Pedidos_Produtos', 'id_pedido', 'id')

hasMany model relation returns empty array. lLaravel Framework 5.5.40

This is my first time posting here, sorry if i input something incorrectly.
So i have Forums.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Forums extends Model
{
protected $table ='forums';
public $primaryKey='id';
public function section()
{
return $this->belongsTo(Section::class,'id');
}
}
and Section.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Section extends Model
{
public function forums()
{
return $this->hasmany(Forums::class,'section_id');
}
}
I fallowed tutorial in which it was shown that using
$section=Section::find($id)->forums;
i should get all the forums that had fk equal to section $id, however ir returns empty array.
I tried to output sql in terminal using:
$order = App\Section::find(2)->forums()->toSql()
where 2 is sections table id and got:
select * from `forums` where `forums`.`section_id` is null and `forums`.`section_id` is not
null"
so no wonder it returns empty array
however if i try to get section related to forum it works perfectly.
How could i fix this?
Changing hasmady to hasMany didn't fix it
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('Forums', function (Blueprint $table) {
$table->increments('id');
$table->string('Name');
$table->string('Description');
$table->integer('topics');
$table->integer('Comments');
$table->integer('Last_Post_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('Forums');
}
}
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddToUsers extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('Forums', function (Blueprint $table)
{
$table->integer('Section_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
}
}
can't seem to find sections shema though i have it's table in database or is because that shema isn't in project folder, because im not getting errors that table or col can't be found?

Save inserts empty row Laravel 5.3

I'm trying to make Laravel ORM working and it keeps inserting empty records in database. The ID created_at and updated_at are correctly inserted but the values are not. Here are the files:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class TesterTest extends Model
{
protected $fillable = ['name','value'];
public $name;
public $value;
}
The migration file:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTestTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('my_tests', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('value');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('my_tests');
} }
And this is how Im calling it:
$flight = new TesterTest;
$flight->name = "Tester1";
$flight->save();
There is a something Im missing but can't figure it out.
I would say that adding in public $name; and public $value; in your model is causing problems. Try removing those two lines.

Categories