I am using latest Laravel. I have a model Car - id | name | * timestamp columns:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Car extends Model{
protected $fillable = [
'name'
];
}
Cars migration:
public function up()
{
Schema::create('cars', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('name')->nullable();
$table->timestamps();
});
I am trying to save new row in cars table in the controller:
$car = new Car();
$car->name = 'example';
$car->save();
, but for $car->save(), I am getting this error:
Call to undefined method App\Models\Car::setCreatedAt()
Even, If I create new migration/model create_table_test (table with the same columns), I am getting the same error.
EDIT with stacktrace:
65 BadMethodCallException in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
64 Illuminate\Database\Eloquent\Model:throwBadMethodCallException in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:36
63 Illuminate\Database\Eloquent\Model:forwardCallTo in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:1614
62 Illuminate\Database\Eloquent\Model:__call in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasTimestamps.php:47
61 Illuminate\Database\Eloquent\Model:updateTimestamps in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:791
60 Illuminate\Database\Eloquent\Model:performInsert in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:663
59 Illuminate\Database\Eloquent\Model:save in /mnt/e/xampp/htdocs/room2/project/app/Http/Controllers/Admin/CarsController.php:33
58 App\Http\Controllers\Admin\CarsController:importCars/mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Controller.php:54
57 call_user_func_array in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Controller.php:54
56 Illuminate\Routing\Controller:callAction in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php:45
55 Illuminate\Routing\ControllerDispatcher:dispatch in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Route.php:219
54 Illuminate\Routing\Route:runController in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Route.php:176
53 Illuminate\Routing\Route:run in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Router.php:680
52 Illuminate\Routing\Router:Illuminate\Routing{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:30
51 Illuminate\Routing\Pipeline:Illuminate\Routing{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/barryvdh/laravel-stack-middleware/src/ClosureHttpKernel.php:30
50 Barryvdh\StackMiddleware\ClosureHttpKernel:handle in /mnt/e/xampp/htdocs/room2/project/vendor/helthe/turbolinks/StackTurbolinks.php:51
49 Helthe\Component\Turbolinks\StackTurbolinks:handle in /mnt/e/xampp/htdocs/room2/project/vendor/barryvdh/laravel-stack-middleware/src/ClosureMiddleware.php:36
48 Barryvdh\StackMiddleware\ClosureMiddleware:handle in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163
47 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
46 Illuminate\Routing\Pipeline:Illuminate\Routing{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php:41
45 Illuminate\Routing\Middleware\SubstituteBindings:handle in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163
44 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
43 Illuminate\Routing\Pipeline:Illuminate\Routing{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php:43
42 Illuminate\Auth\Middleware\Authenticate:handle in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163
41 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
40 Illuminate\Routing\Pipeline:Illuminate\Routing{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php:75
39 Illuminate\Foundation\Http\Middleware\VerifyCsrfToken:handle in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163
38 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
......
I just re-install Laravel.
Delete vendor folder ;
Delete composer.lock;
composer update in the console.
Thanks, #Jonas Staudenmeir for your help.
Related
I have a table hobbies like this:
-id
-name
-parent_id
and my model
public function sub_hobbies(){
return $this->hasMany(Hobbies::class, 'parent_id');
}
public function parent_hobbies(){
return $this->belongsTo(Hobbies::class, 'parent_id');
}
public function allsub(){
return $this->sub_hobbies()->with('allsub');
}
public function allparent(){
return $this->parent_hobbies()->with('allparent');
}
What i want is to get all hobbies which are not child or grand child of given hobbies
example i have this list:
-hobbies 1
-hobbies 11
-hobbies 12
-hobbies 121
-hobbies 122
-hobbies 13
-hobbies 2
-hobbies 21
-hobbies 22
-hobbies 221
-hobbies 222
-hobbies 23
-hobbies 3
-hobbies 31
-hobbies 32
-hobbies 321
-hobbies 322
-hobbies 33
if i give id of hobbies 1, i want all hobbies except hobbies 11, 12, 121, 122, 13
So i found a little way to make run what i want to do but i don't know if it's the right way:
// get hobbies and exlude given hobbies and his child line
public function scopeIsNotLine($query, $id){
// get all hobbies to exclude by id and his child line
$hobbies = Hobbies::with('allsub')->where('id', $id)->get()->toArray();
// transform result to array of id of hobbies to exclude
$exclude = collect($this->flatten($hobbies))->map(function ($item) {
return collect($item)
->only(['id'])
->all();
})->flatten()->all();
// get hobbies where id not in exluded hobbies
return $query->whereNotIn('id', $exclude)->whereDoesntHave('is_archive');
}
// transform nested result to simple array without nest hierarchie
private function flatten($array) {
$result = [];
foreach ($array as $item) {
if (is_array($item)) {
$result[] = array_filter($item, function($array) {
return ! is_array($array);
});
$result = array_merge($result, $this->flatten($item));
}
}
return array_filter($result);
}
Firts i retrieve the hobbies selected with his all child and grand child
Second, i transform the result into flatten array (list all without nested relationship) with the function flatten that i created
Third i transform again into array of id
Fourth i use this array in whereNotIn to retrieve all hobbies and exclude the hobbies selected and his child line
Fifth i used my scope like Hobbies::isNotLine('the-id-selected')->get();
In result i got all hobbies excluding the hobbies i selected, and his child and grand child
I'm Importing My Users through Excel using the Laravel Excel Package
I want to create a profile Model before importing users. How do I do this?
The user table has a 1: 1 relationship with the profile table. This means that each user has one profile
User Table :
id username password is-admin created_at updated_at department_id
1 4480115617 $2y$10$HUBeOzDlTvaJKmI8d5GXJ.qzbqsDcDooi4WG0BrOAHOE9Ce3HMgC6 1 2021-04-16 10:07:34 2021-06-24 04:51:18 10
52 4480124152 $2y$10$.hOMGBCdcrBNx6UbQ4vAOeInnma6mjnztRxL2k8kpV/vK2dEWrj8O 0 2021-07-08 08:01:07 2021-07-08 08:01:07 1
53 12345678910 $2y$10$5d.FMSRyf/KT8bOtQYaSA.BZMLVEKFgjiXL/pjfHCMXmZ7tbZgnPW 1 2021-07-08 08:02:07 2021-07-08 08:02:07 2
54 4420827661 $2y$10$TE8biYPPHhv7ZdUfmY11sO9.7QXOaqKAyWkOEbgsBxJi2uq2iLFs2 1 2021-07-13 06:50:38 2021-07-13 06:50:38 3
Profile Table :
id user_id avatar_src phone address email created_at updated_at field_id name family father national_code
6 1 users/avatars/default.jpg 0xxxxxxxxxxx یزد aa#asdag.com (NULL) 2021-06-24 04:51:18 (NULL) محمد غریب
21 52 users/avatars/52.jpg 09134576502 adasdasdasdasdas mohamm#taho.com 2021-07-08 08:01:08 2021-07-13 06:54:05 (NULL) محمد کریمی
22 53 users/avatars/default.jpg 09134575052 daasdasd asda#yaho.com 2021-07-08 08:02:07 2021-07-08 08:02:07 (NULL) مسعود رامینی
23 54 users/avatars/default.jpg 09134576502 قلثقلقثقثقثث reza#yaho.com 2021-07-13 06:50:38 2021-07-13 06:50:38 (NULL) مهدی رضایی
Assuming you are using a custom import class, if not you many want to use a custom import class by creating a new class called UsersImport in app/Importsdefined in the docs.
UsersImport.php
namespace App\Imports;
use App\User;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
class UsersImport implements ToCollection
{
public function collection(Collection $rows)
{
foreach ($rows as $row)
{
// We are creating an instance to use it to create the profile
$user = User::create([
'username' => $row[0], //or name of the col with $row['username']
'password' => $row[1],
'is-admin' => $row[2],
'department_id' => $row[3]
]);
// create the profile using $user and one-to-one relationship
// assuming your relationship is profile() defined in User Model
$user->profile()->create([
'avatar_src' => $row['avatar_src'],
'phone' => $row['phone'],
//... your other columns
]);
}
}
}
Next call your method in Database Seeder with Excel::import(new UsersImport, storage_path('Pathtolfile.xlsx'));
I have 2 table products and variants, with a hasMany relationship, the structure is below :
Product Model :
public function variants()
{
return $this->hasMany(Variant::class);
}
Variant Model :
public function product()
{
return $this->belongsTo(Product::class);
}
Product Table :
| id name image manufacturer
| 1 T-Shirt t-s.jpg docomo
| 2 Short Skirt s-skirt.jpg docomo
Variant Table :
| id product_id name price sku quantity
| 1 1 S 30 ts-s 100
| 2 1 M 32 ts-m 100
| 3 1 XL 35 ts-xl 100
| 4 2 S 23 sk-s 100
| 5 2 M 25 sk-m 100
| 6 2 XL 28 sk-xl 100
I can save data on Variant model (child table) from Product model as :
public function store(Request $request)
{
$q = new Product;
$q->name = $request->name;
$q->save();
// Below child table
$q->variants()->createMany($request->variant);
}
I can store data, but the problem is that, how can I update child table? [It can be create, update or delete]
I tried with sync() method, but didn't work. Its for manyToMany relationship.
public function update(Request $request)
{
$q = Product::findOrFail($request->id);
$q->name = $request->name;
$q->save();
// Below child table update
// $q->variants()->sync($request->variant); // not worked
}
sync() works in manyToMany relationship. I need the same for hasMany relationship.
How can I do that?
Unfortunately there is no sync method for hasMany relations. It's pretty simple to do it by yourself. You can simple delete the rows and insert them all again.
public function update(Request $request, Product $product)
{
$product->update(['name' => $request->name]);
// Below child table update
$product->variants()->delete();
$product->variants()->sync($request->variant);
}
There are two tables which is many to many relation:
User:
<?php class User extends Eloquent {
public function roles()
{
return $this->belongsToMany('Role');
}
}
Role:
class Role extends Eloquent {
public function users()
{
return $this->belongsToMany('User');
}
}
I have no problem to get the users with all the fields and convert it to json:
$role = Role::find($id)->users()->get()->toArray();
var_dump($role);
But when I'm trying to only retrieve the user id field, I encountered a problem to convert it to json, here is my code: (If I don't call ->get()->toArray(), the var_dump has no problem.)
$role = Role::find($id)->users()->select(array('id'))->get()->toArray();
var_dump($role);
Any idea? Thanks
Edit:
The error message:
Slim Application Errorbody{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}Slim Application ErrorThe application could not run because of the following error:DetailsType: Illuminate\Database\QueryExceptionCode: 23000Message: SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in field list is ambiguous (SQL: select id, users.*, role_user.role_id as pivot_role_id, role_user.user_id as pivot_user_id from users inner join role_user on users.id = role_user.user_id where role_user.role_id = role_1)File: /Users/Public/Website/cast/vendor/illuminate/database/Illuminate/Database/Connection.phpLine: 555Trace#0 /Users/Public/Website/cast/vendor/illuminate/database/Illuminate/Database/Connection.php(283): Illuminate\Database\Connection->run('select id, u...', Array, Object(Closure))
<div>#1 /Users/Public/Website/cast/vendor/illuminate/database/Illuminate/Database/Query/Builder.php(1312): Illuminate\Database\Connection->select('selectid,u...', Array)
#2 /Users/Public/Website/cast/vendor/illuminate/database/Illuminate/Database/Query/Builder.php(1302): Illuminate\Database\Query\Builder->runSelect()
#3 /Users/Public/Website/cast/vendor/illuminate/database/Illuminate/Database/Query/Builder.php(1289): Illuminate\Database\Query\Builder->getFresh(Array)
#4 /Users/Public/Website/cast/vendor/illuminate/database/Illuminate/Database/Eloquent/Builder.php(416): Illuminate\Database\Query\Builder->get(Array)
#5 /Users/Public/Website/cast/vendor/illuminate/database/Illuminate/Database/Eloquent/Relations/BelongsToMany.php(145): Illuminate\Database\Eloquent\Builder->getModels()
#6 /Users/Public/Website/cast/app/controllers/Api/v1/TestController.php(24): Illuminate\Database\Eloquent\Relations\BelongsToMany->get()
#7 [internal function]: Api\v1\TestController->testRelation('role_1')
#8 /Users/Public/Website/cast/vendor/slim/slim/Slim/Route.php(173): call_user_func_array(Array, Array)
#9 [internal function]: Slim\Route->Slim{closure}('role_1')
#10 /Users/Public/Website/cast/vendor/slim/slim/Slim/Route.php(462): call_user_func_array(Object(Closure), Array)
#11 /Users/Public/Website/cast/vendor/slim/slim/Slim/Slim.php(1326): Slim\Route->dispatch()
#12 /Users/Public/Website/cast/vendor/slim/slim/Slim/Middleware/Flash.php(85): Slim\Slim->call()
#13 /Users/Public/Website/cast/vendor/slim/slim/Slim/Middleware/MethodOverride.php(92): Slim\Middleware\Flash->call()
#14 /Users/Public/Website/cast/vendor/slim/slim/Slim/Middleware/PrettyExceptions.php(67): Slim\Middleware\MethodOverride->call()
#15 /Users/Public/Website/cast/vendor/slim/slim/Slim/Slim.php(1271): Slim\Middleware\PrettyExceptions->call()
#16 /Users/Public/Website/cast/vendor/illuminate/support/Illuminate/Support/Facades/Facade.php(205): Slim\Slim->run()
#17 /Users/Public/Website/cast/public/index.php(4): Illuminate\Support\Facades\Facade::__callStatic('run', Array)
#18 /Users/Public/Website/cast/public/index.php(4): SlimFacades\App::run()
#19 {main}
Edit 2:
The error was caused by the field in select statement. I changed it to:
$role = Role::find($id)->users()->select(array('users.id'))->get()->toArray();
var_dump($role);
It now returns some value. But unfortunately it still returns all the fields instead of only 'users.id' field.
According to Taylor Otwell it is not currently possible to select the columns to return with belongsToMany: https://github.com/laravel/laravel/issues/2679
What about this solution:
Role
class Role extends Eloquent {
public function users()
{
return $this->belongsToMany('User')->select('id');
}
}
And then
$roles = Role::find($id)->with('users')->get();
$users = $roles->users;
$usersId = $users->lists('id');
Here is the final working version based on Antoine Augusti's answer:
Role.php:
<?php
class Role extends Model {
public function users()
{
//return $this->belongsToMany('User');
return $this->belongsToMany('User')->select('users.id');
}
}
My code to list all the users id:
$roles = Role::find($id);
$users = $roles->users();
$usersId = $users->lists('users.id');
var_dump($usersId);
The usersId will show only the user id in an array. But I think the $users still include all the fields.
Anyway it solved my problem although it's not perfect. Thanks Antoine Augusti.
I'm trying to get the id of last inserted record in the Db. But i'm getting the error
Parse error: syntax error, unexpected T_RETURN in Z:\www\CI4\application\models \report_model.php on line 69
my model:
function getLastInserted() {
$query ="SELECT $id as maxID from info where $id = LAST_INSERT_ID()"
return $query; //line 69
}
my controller:
function index()
{
$id=$this->report_model->getLastInserted();
$this->load->view('u_type1',$id);
}
Assuming you are using the CI database library, you can use $this->db->insert_id().
function getLastInserted() {
return $this->db->insert_id();
}
I think you are missing a ; on line 67 after the last ".
if you want to get last id without insert function
$this->db->select('id')->order_by('id','desc')->limit(1)->get('table_name')->row('id');