I have model:
class Header extends Model
{
use HasFactory;
public function getRouteKeyName()
{
return 'slug';
}
}
my controller:
public function show($id)
{
$headers = DB::table('headers')->find($id);
$blocks = DB::table('blocks')->where('header_id', $id)->get();
return view('test', compact('headers', 'blocks'));
}
my route:
Route::get('/{id}', [MainController::class, 'show'])->name('show');
but I can't show slug, I see localhost:8000/id
error: Attempt to read property "id" on null
You are using getRouteKeyName which is useful for Route-Key binding. But your route is not set up that way.
It also does not help you with the find() method in the Model.
Also, you are not using your model in your DB call. Any methods or properties defined in your model will therefore not be used.
And you should set up relationships to get related data.
Respecting your current route, you should do something like this:
class Header extends Model
{
use HasFactory;
/**
* The primary key associated with the table.
*
* #var string
*/
protected $primaryKey = 'slug';
// ^-- this is what you use to tell Model what column to use for find()
// only use this if you do route-model binding
public function getRouteKeyName()
{
return 'slug';
}
// relationship to find all blocks that belong to this header_id
public function blocks()
{
return $this->hasMany(\App\Model\Blocks::class);
}
}
Then for the DB Call:
public function show($id)
{
$header = Headers::find($id);
$blocks = $header->blocks ?? [];
return view('test', compact('header', 'blocks'));
}
Related
I have two models Product and Images. I changed the route key name on the product model to use the slug field and i'm now unable to load the hasMany relationship with the Image Model
Here is the Product Model
class Product extends Model
{
protected array $with = ['images'];
public function getKeyName()
{
return 'slug';
}
protected array $guarded = [];
public function images() : HasMany
{
return $this->hasMany(Image::class, 'product_id');
}
}
and the Image model
class Image extends Model
{
protected array $guarded = [];
public function image() : BelongsTo
{
return $this->belongsTo(Product::class);
}
}
so when I try
Product::first()->images
it just returns an empty collection
but without overriding the getKeyName() method, everything works fine
getKeyName() will get the primary key for the model. it supports to return id, after you change it to slug, it will return slug
And hasManyHere's the source code ;
The third parameter LocalKey will use getKeyName() when it's empty.
If you still want to use hasMany, you need to pass the third parameter like this:
public function images()
{
return $this->hasMany(Image::class, 'product_id', 'id');
}
This will convert the Eloquent query to database query, which will take the right local key products.id.
I'am beginner in Laravel. I have project in Laravel 5.8.
I have User model:
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
use psCMS\Presenters\UserPresenter;
use scopeActiveTrait;
public static $roles = [];
public $dates = ['last_activity'];
// ...
public function scopeHistory()
{
return $this->hasMany('App\UserLoginHistory');
}
// ...
}
and UserLoginHistory:
class UserLoginHistory extends Model
{
protected $quarded = ['id'];
public $timestamps = false;
protected $fillable = ['user_id', 'date_time', 'ip'];
public function user()
{
return $this->belongsTo('App\User');
}
}
I want show user login history by this code:
User::history()->where('id', $idAdmin)->orderBy('id', 'desc')->paginate(25);
but it's not working.
This function not working - I haven't got results.
How can I fixed it?
First of all, you are defining your relationship as a scope (prefixing the relationship with the scope keyword). Try updating your model relationship to this:
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
Then, given your query, it seems that you want to get all the UserLoginHistory
records for a given User. You could accomplish this in two ways (at least).
From the UserLoginHistory model itself, constraining the query by the foreign key value:
$userId = auth()->id(); // get the user ID here.
$results = UserLoginHistory::where('user_id', $userId)->paginate(15);
// ^^^^^^^ your FK column name
From the User model using your defined relationship:
$userId = auth()->id(); // get the user ID here.
$results = User::find($userId)->history;
The downside of the second approach is that you'll need to paginate the results manually.
in your User model you should define your relation by this way :
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
then if you would like to select with history model you can do that with WhereHas() method :
User::whereHas(['history'=>function($q) use ($idAdmin) {
$q->where('id',$idAdmin)
}])->orderBy('id', 'desc')->paginate(25);
You must be do this changes
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
usage
$user = User::find($idAdmin);
$userHistories = $user->history()->latest()->paginate(25);
or get user with all history
User::with('history')->find($idAdmin);
// Post model
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category')->withTimestamps();
}
}
// Category model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function posts()
{
return $this->belongsToMany('App\Post')->withTimestamps();
}
}
There are three database tables users, articles and a joining table article_users_comments, which holds the comment, the user id commented the article and the commented article id.
I can achieve the following thing with pure SQL join, but I want to do it with Eloquent, I thought that it would be quite easy, but I am kind of confused right now.
I have been trying different things, but it still doesn't work.
// User
class User extends Authenticatable implements MustVerifyEmail,CanResetPassword{
public function comments()
{
return $this->hasMany('App\ArticleComments');
}
}
// Article
class Article extends Model{
public function getArticles(){
$articles = Article::paginate(3);
return $articles;
}
public function getSingleArticle($title){
$article = Article::where('title','=',$title)->get();
return $article;
}
public function articleComments()
{
return $this->hasMany('App\ArticleComments');
}
}
// ArticleComments
class ArticleComments extends Model{
protected $table = 'article_users_comments';
public $timestamps = false;
public function article()
{
return $this->belongsTo('App\Article');
}
public function user()
{
$this->belongsTo('App\User');
}
}
// ArticleController(showing only the show method), which passes the data to the certain view
instantiating the Article Model
class ArticleController extends Controller{
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($title)
{
$removeDashesFromUrl = str_replace('-',' ',$title);
$am = new Article();
$data = $am->getSingleArticle($removeDashesFromUrl);
return view('article',['article'=>$data]);
}
}
I want to get the comments and the users(which have commented the article) for a certain certain article.
You should set the foreign key in your articleComments and article relations:
Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. However, you may pass a custom key name as the second argument to the belongsTo method:
Article Model
public function articleComments()
{
return $this->hasMany('App\ArticleComments','commented_article_id');
}
ArticleComments Model
public function article()
{
return $this->belongsTo('App\Article','commented_article_id');
}
You can get the comments from a article using the relation:
$article = Article::find($id);
$article->articleComments; // This will return all comments for the given article
You could use a foreach loop and access each attribute from each comment:
foreach($article->articleComments as $comment)
{
echo $comment->id;
echo $comment->user->id;
echo $comment->user->username;
.
.
.
}
You can access the user and any of his attributes just calling the relation in your comment like i did above.
For more info: click here.
Note: i strongly recommend you changing your model name to Comment, we don't use model names in the plural, always in singular.
My model Dispatch has a field invoice_id.
It is a foreign key so i can get the invoice details using the below code:
protected $fillable = [
'id',
'truck_no',
'driver_name',
'driver_phone',
'gps_details',
'invoice_id',
];
public function invoice(){
return $this->belongsTo('App\Invoice')->select('id','invoice_no','permit_id');
}
Now I want to get the value permit_id from invoice() so i can use it to get the details of the Permit.
permit_id = id of Permit model
So I use the below code to get the permit data.
public function permit(){
return $this->hasOne('App\Permit','id',$this->invoice()->permit_id);
}
Update:
My Invoice Model has :
class Invoice extends Model
{
protected $fillable = [
'id',
'invoice_no',
'invoice_date',
'permit_id',
];
public function permit(){
return $this->hasOne('App\Permit', 'id', 'permit_id');
}
}
My Permit Model has:
class Permit extends Model
{
protected $fillable = [
'permit_type',
'permit_no',
'application_no',
'supply_unit',
'supply_unit_id' ,
];
public function supplyunit(){
return $this->hasOne('App\SupplyUnit','id','supply_unit_id');
}
}
And as per suggestions i have added below code in my Dispatch Model:
class Dispatch extends Model
{
protected $fillable = [
'id',
'truck_no',
'driver_name',
'driver_phone',
'gps_details',
'invoice_id',
];
public function invoice(){
return $this->hasOne('App\Invoice','id','invoice_id');
}
public function permit(){
return $this->hasOne('App\Permit','id','permit_id');
}
}
But it doesn't work. What should i do to achieve the above? Is there any other solutions please suggest.
Assuming each invoice has one permit, your relationship definition should look like this:
public function permit(){
return $this->hasOne('App\Permit', 'id', 'permit_id');
}
Edit: If invoice belongs to permit, which is the inverse, your relationship would look like this instead:
public function permit(){
return $this->belongsTo('App\Permit', 'permit_id');
}
Edit: Based on your updated question, I think you got the relationship definitions a bit wrong. The following should work:
Since you have an invoice_id column in App\Dispatch, it means that each App\Dispatch belongs to an invoice.
In App\Dispatch, your relationship definition should be as follows:
public function invoice() {
return $this->belongsTo('App\Invoice');
}
// permit does not belong to `App\Dispatch` as a direct relationship
// it should be removed
In App\Invoice, your relationship definition should be as follows:
public function dispatch() {
return $this->hasOne('App\Dispatch');
}
public function permit() {
return $this->belongsTo('App\Permit');
}
In App\Permit, your relationship definition should be as follows:
public function invoice() {
return $this->hasOne('App\Invoice');
}
To then retrieve the permit id from an Invoice model, you would do
$invoice->permit->id;
Change this line
return $this->belongsTo('App\Invoice')->select('id','invoice_no','permit_id');
To
return $this->belongsTo('App\Invoice');
And add the following code on Invoice
public function permit(){
return $this->belongsTo('App\Permit');
}
And you can access as
Dispatch::find($id)->invoice->permit->id;
Or if you want all the information
Dispatch::find($id)->invoice->permit;
i'm using a data table with name auct_lots_full for my Lot.php model, where primary key is lot_id, in order everything to work i used Sofa/Eloquence extension, Mappable. So this is my model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Sofa\Eloquence\Eloquence;
use Sofa\Eloquence\Mappable;
class Lot extends Model
{
use Eloquence, Mappable;
protected $table = 'auct_lots_full';
protected $maps =[
'id' => 'lot_id',
];
public function scopeFilter($query, QueryFilter $filters)
{
return $filters->apply($query);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
}
But he problem is that in some cases it keeps looking for id column as primary key. For example in LotsController.php i have this problem here :
public function show($id)
{
$lot = Lot::find($id);
return view('lots.show')->withLot($lot);
}
But i fix this problem with this solution:
public function show($id)
{
$lot = Lot::where('lot_id', $id)->first();
return view('lots.show')->withLot($lot);
}
But i understand that is just a solution for only this function...
So the same problem i have in CommentsController.php:
public function show()
{
$comments = Comment::orderBy('id', 'desc')->paginate(30);
return view('comments.browse', compact('comments'));
}
And i don't know how to fix it. Could any one explain me why is this happening? Is there a better way than use an extension? How i can fix this error in CommentsCotroller.php ?
This is the Comment.php model:
<?php
namespace App;
class Comment extends Model
{
public function lot()
{
return $this->belongsTo(Lot::class);
}
public function User()
{
return $this->belongsTo(User::class);
}
}
There is a primaryKey variable in your Model file which is id by default.
/**
* The primary key for the model.
*
* #var string
*/
protected $primaryKey = 'id';
If you override this variable in Lot model file. So your primary key will be lot_id instead of id as in default. Simply add this;
protected $primaryKey = 'lot_id';
So actually i find a proper way to do it with out Sofa/Eloquence extension, using not only foreign key but also a local key in many to many relationship. So this is the new code:
so for Lot.php i did this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Lot extends Model
{
protected $table = 'auct_lots_full';
protected $primaryKey = 'lot_id';
public function scopeFilter($query, QueryFilter $filters)
{
return $filters->apply($query);
}
public function comments()
{
return $this->hasMany(Comment::class,'lot_id', 'lot_id');
}
}
Than i did same for the Comment.php model:
<?php
namespace App;
class Comment extends Model
{
public function lot()
{
return $this->belongsTo(Lot::class, 'lot_id', 'lot_id');
}
public function User()
{
return $this->belongsTo(User::class);
}
}
So what we see above, in Lot.php model, function comments i pass foreignKey: 'lot_id' in auct_lots_full table and localKey 'lot_id' in comments table witch refers to the auct_lots_full table. In Comment.php model wi did the same but in case instead of localKey it is ownerKey. Im a bad at explaining so i will attach some images to make sense.
Lot.php
Comment.php