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
Related
I want to fetch only one columns which has name image_url from relationship table. relationship on table is belongsTO.
i am confused how to fetch only single column value with belongsTo relation.
below is my model.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class PropertyImageGallery extends Model
{
use HasFactory;
protected $fillable = ['property_id', 'name', 'size','image_url'];
public function property()
{
return $this->belongsTo(Property::class);
}
}
please help me.
You can try this:
public function property()
{
return $this->belongsTo(Property::class)->select(['property_id', '...']);
}
BelongsTo relationship like below:
public function parent()
{
return $this->belongsTo(Parent::class,'foreign_key','owner_key');
}
it would be:
public function property(){
return $this->belongsTo(Property::class,'property_id','id');
}
you should call it like this in your controller :
$yourParentElement = ParentModel::find(1);
return $yourParentElement ->Property->image_url ;
check this for more infos: Eloquent: Relationships (Belongs To)
Am new to laravel, I have issues trying to connect this tables: plans,users and loans even after reading the docs,
I have a plans tables that have all my plans, then I have a users table and loans table, my loans table has a user_id and a plan_id, all I want is to pull the records for plans and the users in the loan model.
Loanplan.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loanplan extends Model
{
//
protected $fillable = [
'title',
'amount',
'interest',
'repayment_month',
'status',
];
public function loan()
{
return $this->belongsTo('App\loan');
}
}
my loan model:
Loan.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
protected $table = 'loans';
//
protected $fillable = [
'id',
'user_id',
'loanplan_id',
'payment_made',
'status',
];
public function user()
{
return $this->belongsTo('App\User');
}
public function loanplan()
{
return $this->belongsTo('App\Loanplan');
}
}
I want get all the loan plans and users table records with plan_id and user_id as foreign respectively respectively in my LoanController.
I think the problem is with the customization of the loans table name in the Loanplan model.
According with your descriptions you need the followings setup:
A User can access to one or many Loans
users 1---m plans
A Loan belongs to a Loanplan // here I'm using Loanplan because that is your model name.
loans 1---m plans
So, this means:
User.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'users';
//
protected $fillable = [
'id',
//
];
public function loans()
{
return $this->hasMany(Loan::class);
}
//
}
Loan.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
protected $table = 'loans';
//
protected $fillable = [
'id',
'user_id',
'loanplan_id',
//
];
public function user()
{
return $this->belongsTo(User::class);
}
public function plan()
{
// Notice that here I'm specifying the foreign key:
return $this->belongsTo(Loanplan::class);
}
//
}
Loanplan.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loanplan extends Model
{
protected $table = 'plans';
//
protected $fillable = [
'id',
//
];
public function loans()
{
return $this->hasMany(Loan::class);
}
//
}
So with this, you can access the information in your LoanController.php:
LoanController.php
public function myCoolMethod()
{
// get a user
$user = User::first();
// access his/her loans
$loans = user->loans;
//
// get a loan plan
$plan = Loanplan::first();
// access its loans
$loans = plan->loans;
//
}
I strongly suggest you to read the Laravel Documentation regarding relationships and also a course for database design. Have a good day mate.
Loanplan.php is missing the protected $table = "plans" variable
Same file,
public function loan()
{
return $this->belongsTo('App\loan');
}
the relationship should be hasOne or hasMany, not belongsTo.
Moreover, the name of the class should have Loan with capital L.
public function loan()
{
return $this->...('App\Loan');
}
First of all add protected $table = 'plans'; to your Loanplan model since the table name is 'plans'
Loanplan Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loanplan extends Model
{
protected $table = 'plans';
protected $fillable = [
'title',
'amount',
'interest',
'repayment_month',
'status',
];
public function loan()
{
return $this->hasOne('App\loan'); // or hasMany
}
}
?>
Loan Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
protected $table = 'loans';
//
protected $fillable = [
'id',
'user_id',
'loanplan_id',
'payment_made',
'status',
];
public function user()
{
return $this->belongsTo('App\User');
}
public function loanplan()
{
return $this->belongsTo('App\Loanplan');
}
}
?>
add this to the User Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function Loan()
{
return $this->hasOne('App\Loan'); // or hasMany
}
}
?>
First, you have to check if the model already querying from table that you created before. Laravel will automatically access table base on your class name.
Note that we did not tell Eloquent which table to use for our Flight model. By convention, the "snake case", plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the Flight model stores records in the flights table.
You can read it from this documentation
Second, make sure you call the right class. From Loanplan.php in the loan() method it's not using uppercase for the first letter.
Third, try to state the foreign key and primary key. You can also check how to do it in the documentation.
I use eloquent with soft delete .I'm getting error because of my query still select data that already use softdelete here is my model
User Model
class User extends Authenticatable
{
use Notifiable, HasRoles, SoftDeletes;
protected $guard_name = 'web';
protected $fillable = [
'username', 'password'
];
protected $dates = ['deleted_at'];
}
for example I've 100 user and I deleted 1 user with softdelete . then I try to
$a = User::all();
dd($a);
I get 99 user . It works! but after I use it relation It doest work here what I do
This is my Parent table and Model
table
|id|user_id|parent_id|
Note : user_id and parent_id are FK in user.id table
class Parent extends Model
{
protected $table = 'parent';
public function user()
{
return $this->belongsTo('App\User');
}
}
$getParent = Parent::with('user')->get();
when I dd($getParent); why I still get null data from user_id that I already use soft deleted ?
UPDATE model User : after I put whereNull I still getting user that I alredy soft deleted
public function user()
{
return $this->belongsTo('App\User')->whereNull('users.deleted_at');
}
https://laravel.com/docs/5.7/eloquent#querying-soft-deleted-models
...
public function customerAddress()
{
return $this->hasOne(Addresses::class, "id", "id_address")->withTrashed();
}
...
Ok, here's what I think is going on...
With soft delete the ondelete event doesn't work (meaning that related models is not deleted). I'm not sure if that changed in later versions of Laravel, but I don't think so. Also deleting User would still not affect the parent model, since you haven't defined the relationship between User and Parent (in the User model), only between Parent and User.
Try defining the relationship in User and then override the boot() function, that sits in the Model class. (This is untested code, but something like this should do the job)
class User extends Authenticatable
{
use Notifiable, HasRoles, SoftDeletes;
protected $guard_name = 'web';
protected $fillable = [
'username', 'password'
];
protected $dates = ['deleted_at'];
// Override Model boot function
protected static function boot()
{
parent::boot();
static::deleting(function ($users) {
foreach ($users->parents()->get() as $parent) {
$parent->delete();
}
});
}
// Define relationship with parent model
public function parents()
{
$this->hasMany('App\Parent');
}
}
You can put a constraint on the Eager Load:
public function groups()
{
return $this
->belongsToMany('Group')
->whereNull('group_user.deleted_at') // Table `group_user` has column `deleted_at`
->withTimestamps(); // Table `group_user` has columns: `created_at`, `updated_at`
}
Instead of HARD deleting the relationship using:
User::find(1)->groups()->detach();
You should use something like this to SOFT delete instead:
DB::table('group_user')
->where('user_id', $user_id)
->where('group_id', $group_id)
->update(array('deleted_at' => DB::raw('NOW()')));
I have a model hotel.php to insert hotel data.insert data using create() but it dosen't return id, the returning collection hasn't id field!
Controller.php
/** "/user/2/create" */
public function store(User $user, HotelRequest $request)
{
$slug = (new hotel)->uniqueSlug( $request->name );
$request->merge([
'cat_id' => 1,
'slug' => $slug,
'created_by' => auth()->user()->id,
]);
$hotel = $user->hotels()->create( $request->all() );
dd($hotel);
................
hotel.php (model)
namespace App;
use Illuminate\Http\UploadedFile;
use Illuminate\Database\Eloquent\Model;
class hotel extends Model
{
protected $fillable = ['name', 'description','address','street','city','email',
'phone','web','cat_id','slug','created_by'];
protected $primaryKey = 'slug';
/**
unique slugs genarating
*/
protected $slug_guards = ['create','room'];
public $incrementing = false;
User.php (model)
public function hotels( )
{
return $this->hasmany('App\Hotel');
}
and the final result
It dosen't have id attribute. I need id to upload image!
NB: I changed that primarykey to default 'id' but no change in result.
Create_hotels... migration
public function up()
{
Schema::create('hotels', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->integer('created_by');
$table->integer('cat_id');
$table->string('name');
Your hotel model set the primary key as the slug :
protected $primaryKey = 'slug';
What i usually do, is for all my migrations, i set an autoincrements like following :
$table->increments('id');
this way laravel handles everything for you. Each create, update or whatever method handle the id of your items.
With this, you can then return the id of a stored data this way :
$id = create($data)->id;
where $data is your model with new datas. $id should now contain the id value of the newest stored model datas.
You have to change the Hotel model (or remove the whole line):
public $incrementing = true;
You are dumping the data you just inserted into the db which does not contain a id field.
create a show method in your Controller class as follows
public function show(User $user){
dd($user)
}
with a route as follows:
Route::get('user/{user}', 'Controller#show')
In hotel.php before the protected $fillable declaration try adding
protected $guarded = [
'id',
];
In your controllers store() method just after $slug = (new hotel)->uniqueSlug( $request->name );
try adding a $slug->save(); then returned slug should have an ID returned with it.
and/or possible the same similar strategy after line
$hotel = $user->hotels()->create( $request->all() );
by adding $hotel->save();
I changed the primarykey to default id and $incrementing = true; now its returning id of the created data. I changed whole methodes in Controller
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');
}
}