Laravel 5.1 create not working - php

I am new to Laravel 5.1. I'm watching a tutorial video and in video teacher is using this code to insert data in database :
<?php
namespace App\Http\Controllers;
use App\comments;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class CommentController extends Controller
{
public function getCommentNew()
{
$data = array(
'commenter' => 'soheil' ,
'comment ' => 'Test content' ,
'email' => 'soheil#gmail.com' ,
'post_id' => 1 ,
) ;
comments::create( $data );
}
}
I am doing the steps like him but I have a problem , all fields ecept created_at and updated_at will be empty like this :
this is my comments model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class comments extends Model
{
protected $fillable = ['commenter,email,post_id,comment,approved'];
public function post(){
return $this->belongsTo('App\posts');
}
}
and this is migration :
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCommentsTable extends Migration
{
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->unsignedinteger('post_id');
$table->string('commenter') ;
$table->string('email') ;
$table->text('comment') ;
$table->boolean('approved');
$table->timestamps();
});
}
public function down()
{
Schema::drop('comments');
}
}

You haven't properly set the $fillable attribute in your Model, try with :
// in your model
protected $fillable = [
'commenter','email','post_id','comment','approved'
];

You have to define column names saperately on fillable array as shempignon described on above answer
Ex: ['column1', 'column2'...]
not in a single string. Each column name needs to be an array element

Try this and it'll be fine :) , you just forgot protected $table = 'comments';
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class comments extends Model
{
protected $table = 'comments';
protected $fillable = ['commenter','email','post_id','comment','approved'];
public function post(){
return $this->belongsTo('App\posts');
}
}

Related

Laravel hasOne() Function Using $this when not in object context

I have 2 models named AdminContent, AdminCategory. I have content_category_id in my admin_contents table. I have category_id and category_name in my admin_categories table. I linked category_id with content_category_id foreign.
I am using the hasOne() function in my Admin Content model. But I get the error Using $this when not in object context!
My main goal is to get content_category_id value from admin_categories table name column
Migrations
// Admin Categories Migration
Schema::create( 'admin_categories', function(Blueprint $table) {
$table->bigIncrements('ctgry_id')->unique();
$table->string('category_name', 50)->unique();
$table->timestamps();
});
// Admin Contents Migration
Schema::create('admin_contents', function (Blueprint $table) {
$table->bigIncrements('cntnt_id')->unique();
$table->string('content_title');
$table->text('content_content');
$table->string('content_slug');
$table->bigInteger('content_category_id');
$table->foreign('content_category_id')->references('ctgry_id')->on('admin_categories');
$table->string('content_status');
$table->string('create_user');
$table->string('content_tags');
$table->string('content_excerpt');
$table->dateTime('posted_at');
$table->timestamps();
});
Models
// AdminContent Model
protected $table = "admin_contents";
protected $fillable = [
'content_title', 'content_content',
'content_category_id', 'content_status', 'create_user','content_tags',
'content_excerpt',
'created_at', 'updated_at'
];
protected $guards = [
'cntnt_id',
];
public function setCategoryName()
{
return $this->hasOne(AdminCategory::class);
}
When I want to access with $this->hasOne(AdminCategory::class) I get this error!
First: relationships in Laravel are based in standardize models, using 'id' as column name for ids. If you are using another name for firstKey, you should add it to relationship definition, as stated in documentation. I mean, your relationship should not work because Eloquent doesn't know which are your tables first keys.
Second: when you define a relationship you should call id from your model. So how are you accessing to $this->hasOne(AdminCategory::class)?
It should be something like AdminContent::with('setCategoryName')
Maybe showing some code from your controller we can give you a more accurate reply.
What I want is this,
I get the blog content with query and print it. But I am printing the content_category_id value as the id value in category table. What I need to do is get the content_category_id and the id value in the category table, the category name linked to that id. Thanks in advance for your help.
Admin Content Model
namespace App\Models\Admin;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class AdminContent extends Model
{
use HasFactory;
protected $table = "admin_contents";
protected $primaryKey = 'cntnt_id';
protected $fillable = [
'content_title', 'content_content',
'content_category_id', 'content_status', 'create_user','content_tags',
'content_excerpt',
'created_at', 'updated_at'
];
protected $guards = [
'cntnt_id',
];
public function _all()
{
return self::all();
}
public static function setCategoryName()
{
return $this->hasOne(AdminCategory::class, 'content_category_id', 'ctgry_id');
}
}
Admin Category Model
namespace App\Models\Admin;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class AdminCategory extends Model
{
use HasFactory;
protected $table = 'admin_categories';
protected $primaryKey = 'ctgry_id';
protected $fillable = [
'category_name', 'updated_at'
];
protected $quards = [
'ctgry_id', 'created_at'
];
}
Post Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Admin\AdminContent;
class PostController extends Controller
{
public function index()
{
return view('frontend.blog');
}
public function getCategoryName()
{
return AdminContent::find(1)->setCategoryName;
}
}
MySQL Tables
https://www.hizliresim.com/2z0337a

Attempt to read property "id" on null laravel 8

Can someone help me?
I have an error Attempt to read property "id" on null Laravel 8 while trying to show my table
Migration Tables
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('username', 20)->unique();
$table->string('password', 20);
$table->enum('level',['admin', 'manager', 'pegawai']);
$table->timestamps();
});
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->foreignId('id_user')
->constrained('users')
->onUpdate('cascade')
->onDelete('cascade');
$table->string('nama_pgw', 50);
$table->string('alamat');
$table->string('no_telp', 13);
$table->string('email', 30)->unique;
$table->timestamps();
});
Employee Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
use HasFactory;
protected $table = 'employees';
protected $fillable = ['nama_pgw', 'username', 'alamat', 'no_telp', 'email'];
public function user(){
return $this->hasOne(User::class);
}
}
User Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use HasFactory;
protected $table = 'users';
protected $fillable = ['username', 'password', 'level'];
public function employee(){
return $this->belongsTo(Employee::class, 'id_user', 'id');
}
}
User Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\User;
class UserController extends Controller
{
public function index()
{
$users = User::get();
return view('user/index', compact('users'));
}
}
Employee Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Employee;
use App\Models\User;
class PegawaiController extends Controller
{
public function index()
{
$pegawai = Employee::get();
return view('pegawai/index', compact('pegawai'));
}
}
This is my view
<select name="id_user" id="username" class="uk-select">
<option>- pilih username -</option>
#foreach ($pegawai as $emp)
option value="{{$emp->users->id}}">{{$emp->users->nama_pgw}}</option>
#endforeach
</select>
Is it any problem on foreign key? I keep checking on typos possibility but everything seems right.
thank you!
Your relation in the employee Model is "user" while you are referring to it in blade view as "users".
Also, to run your code you can update your view:
<select name="id_user" id="username" class="uk-select">
<option>- pilih username -</option>
#foreach ($pegawai as $emp)
<option value="{{$emp->user->id}}">{{$emp->user->nama_pgw}}</option>
#endforeach
</select>
Edited:
I will also suggest optimizing your query by using eager loading. In your current code, it will execute n+1 queries where 1 query to retrieve employees and N queries to retrieve user for each employee
Update it with below code:
class PegawaiController extends Controller
{
public function index()
{
$pegawai = Employee::with(['user'])->get();
return view('pegawai/index', compact('pegawai'));
}
}

laravel boot methods not working in the model

hi im using laravel 8 and im trying to do some code after create or update
like if model has create set created_by = Auth::user()->id ect
and this is my model code
<?php
namespace App\Models;
use Helper;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Auth;
use App\Models\User;
use Spatie\Activitylog\Traits\LogsActivity;
class Account extends Model
{
use Notifiable,SoftDeletes,LogsActivity;
protected static $logAttributes =
[
'number',
'name',
'foreign_name',
'main_account_id',
'user_id',
'account_state_id',
'note',
'balance_limit',
'approved_state_id'
];
protected static $logName = 'accounts';
protected static $logAttributesToIgnore = [ 'updated_at'];
protected $table = 'accounts';
protected $fillable =
[
'number',
'name',
'foreign_name',
'main_account_id',
'user_id',
'account_state_id',
'note',
'approved_state_id',
'balance_limit',
'created_by','deleted_by'
];
public static function boot()
{
parent::boot();
self::creating(function($model){
$model->created_by = Auth::user()->id; // this code work
});
static::updating(function ($model) {
dd('asdf'); // this not working
});
self::deleting(function($model){
dd($model); // this not working
});
self::restoring(function($model){
dd($model); // this not working
});
}
}
now the code in
static::updating(function ($model) {
dd('asdf'); // this not working
});
is not working when i update any account also in delete and restore
the dd('asdf'); not working
any help here thanks ..
Please try to override the booted method instead of boot. It is an update from laravel 7.
protected static function booted()
{
static::created(function ($user) {
//
});
}
Check the official documentation on Using Closures

HasOne create not updating foreign field

I'm using Laravel and I'm trying to create a related record from an array using the method HasOne::create. It inserts the related record, but does not add a new id to main model's foreign field. What am I doing wrong?
Thx
$contact = new Contact();
$contact->company = $data['company'] ?? '';
$contact->comment = $data['comment'] ?? '';
$contact->save();
$contact->address()->create($data['address']);
...
var_dump($contact->address_id); exit();
The relations work fine, all fields specified. By ->get() methods they're returning correct models
var_dump result - null
Also, the $data['address'] contains valid data, specified as fillable at Address model and address_id is fillable for Contact model
UPD:
Contact class:
public function address()
{
return $this->hasOne(Address::class, 'id', 'address_id');
}
Address class:
public function contact()
{
return $this->belongsTo(Contact::class, 'id', 'address_id');
}
$data['address'] contains an array with ['raw' => 'someaddress'], raw field is in $fillable
There's a nice guide on Eloquent Relationships here.
Based on that I just tested the code below and it works fine (using Laravel 5.8)
Migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Cars extends Migration
{
public function up()
{
Schema::create('owners', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('cars', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
$table->integer('owner_id')->unsigned()->index()->nullable();
$table->foreign('owner_id')->references('id')->on('owners');
});
}
public function down()
{
Schema::drop('cars');
Schema::drop('owners');
}
}
Models
//App/Owner.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Owner extends Model
{
protected $fillable = ['name'];
public function car()
{
return $this->hasOne(Car::class);
}
}
//App/Car.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Car extends Model
{
protected $fillable = ['name'];
public function owner()
{
return $this->belongsTo(Owner::class);
}
}
Test
<?php
namespace Tests\Feature;
use App\Owner;
use Tests\TestCase;
class TestCars extends TestCase
{
/**
* A basic feature test example.
*
* #return void
*/
public function testExample()
{
$owner = new Owner(['name' => 'Jack']);
$owner->save();
$owner->car()->create(['name' => 'Nice Car']);
}
}
SQL
select * from cars;
------------
# id, name, created_at, updated_at, owner_id
'1', 'Nice Car', '2019-06-21 13:08:58', '2019-06-21 13:08:58', '1'
select * from owners
-------------
# id, name, created_at, updated_at
'1', 'Jack', '2019-06-21 13:08:58', '2019-06-21 13:08:58'

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

just started with Laravel. I have attached my user and profile models along with the profile controller. My goal is to assign the foreign key uID in the profile table automatically. Any help will be appreciated.
user model file
namespace App;
use Illuminate\Database\Eloquent\Model;
class user extends Model
{
// specify which attributes can be filled out during registration
public $timestamps = false;
protected $fillable=['firstname','lastname','email','password',];
public function profile(){
return $this->hasOne(profile::class,'pID','uID');
}
}
profile model file
namespace App;
use Illuminate\Database\Eloquent\Model;
class profile extends Model
{
//
public $timestamps = false;
protected $fillable = ['summary','uID'];
public function user(){
return $this->belongsTo(user::class,'uID','pID');
}
}
profile migration file
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProfilesTable extends Migration
{
public function up()
{
// create profile table
Schema::create('profiles', function (Blueprint $table) {
$table->increments('pID');
$table->timestamp('created_at')->useCurrent();
$table->string('summary')->default('');
$table->integer('uID')->unsigned();
$table->foreign('uID')->references('uID')->on('users')->onDelete('cascade');
});
}
}
profile controller file
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\profile;
class ProfileController extends Controller
{
public function store(Request $request)
{
// used to store user profile after validation
$this->validate($request,[
'summary' => 'required'
]);
$profile = new profile([
'summary' => $request->get('summary'),
]);
$profile->save();
return redirect()->route('profile.create')->with('success','Profile created');
}
}
Change your migration file,
As you wanted to define your relationship later, So your foreign id field should be nullable.
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProfilesTable extends Migration
{
public function up()
{
// create profile table
Schema::create('profiles', function (Blueprint $table) {
$table->increments('pID');
$table->timestamp('created_at')->useCurrent();
$table->string('summary')->default('');
$table->integer('uID')->nullable()->unsigned();
$table->foreign('uID')
->references('uID')
->on('users')
->onDelete('cascade');
});
}
}
And If you wanted to assign Logged in user after create profile,
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\profile;
class ProfileController extends Controller
{
public function store(Request $request)
{
// used to store user profile after validation
$this->validate($request,[
'summary' => 'required'
]);
$profile = new profile([
'summary' => $request->get('summary'),
'uID' => auth()->user()->id,
]);
$profile->save();
return redirect()->route('profile.create')->with('success','Profile created');
}
}
If you aren't providing value in your program, you need to provide default value on table definition level.
According to your description it seems you are missing to create a profile after creating a user record.

Categories