How to access a class variable from same class - php

In this snippet:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product_variant extends Model
{
protected $primaryKey='variant_id';
public $translationForeignKey = $this->primaryKey;
}
This rule is not working:
public $translationForeignKey = $this->primaryKey;
How can we access this variable that is in the same scope of this class?

Either set the value in a constructor or create a getter to return the value.
// option 1
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product_variant extends Model
{
protected $primaryKey='variant_id';
public $translationForeignKey = '';
// option 1
public function __construct()
{
$this->translationForeignKey = $this->primaryKey;
}
}
// option 2, you dont even need the other property in this method, unless its value may change during execution
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product_variant extends Model
{
protected $primaryKey='variant_id';
// option 2
public function getTranslationForeignKey()
{
return $this->primaryKey;
}
}

At the time of defining the class you can only assign constant values to the class properties. Variables are not allowed here.
You need to do assignment part in the constructor.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product_variant extends Model
{
protected $primaryKey='variant_id';
public $translationForeignKey;
public function __construct()
{
$this->translationForeignKey = $this->primaryKey;
}
}

Related

Class 'app\Models\Job' not found why ? What to do?

I have this command line that doesn't work but I tried namespace app\Models\Job; or use app\Models\Job; or namespace App\Models\Job; or use App\Models\Job;.
I have also tried directly adding App\Models\Job to the command line but it didn't seem to work.
namespace App\Http\Controllers;
use app\Models\Job;
use Illuminate\Http\Request;
class JobController extends Controller
{
public function __construct(){
$this->middleware(['employer','verified'],['except'=>array('index','show','apply','allJobs','searchJobs','category')]);
}
public function index(){
$jobs = Job::latest()->limit(5)->where('status',1)->get();
$categories = Category::with('jobs')->paginate(5);
$companies = Company::get()->random(6);
return view('welcome',compact('jobs','
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Job extends Model
{
use HasFactory;
protected $fillable = ['user_id','company_id','title','slug','description','roles','category_id','position','address','type','status','last_date','number_of_vacancy','experience','gender','salary'];
public function getRouteKeyName(){
return 'slug';
}
public function company(){
return $this->belongsTo('App\Company');
}
public function users(){
return $this->belongsToMany(User::class)->withTimeStamps();
}
public function checkApplication(){
return \DB::table('job_user')->where('user_id',auth()->user()->id)->where('job_id',$this->id)->exists();
}
public function favorites(){
return $this->belongsToMany(Job::class,'favourites','job_id','user_id')->withTimeStamps();
}
public function checkSaved(){
return \DB::table('favourites')->where('user_id',auth()->user()->id)->where('job_id',$this->id)->exists();
}
}
You should do this instead:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Job; // change app to App
class JobController extends Controller
{...

Laravel class 'UserRole' not found

Hi i am trying to use a model for a test but i get Class 'App\UserRole' not found this is my controller where i am calling it
<?php
namespace App\Http\Controllers;
use App\UserRole;
use Illuminate\Http\Request;
class TestController extends Controller
{
public function index()
{
$role = UserRole::get();
die(var_dump($role));
}
}
and this is my model
<?php
use \Illuminate\Database\Eloquent\Model as Eloquent;
class UserRole extends Eloquent
{
public $table = 'role';
public $primaryKey = 'id_role';
public $timestamps = false;
const ADMIN = 1;
const OPERATOR = 2;
const CUSTOMER = 3;
}
I dont know what im missing, i tried to do the same with User model and it works perfect, also my table is created and populated.
Add a namespace to your model
namespace App;
Should look like this:
<?php
namespace App;
use \Illuminate\Database\Eloquent\Model as Eloquent;
class UserRole extends Eloquent
{
public $table = 'role';
public $primaryKey = 'id_role';
public $timestamps = false;
const ADMIN = 1;
const OPERATOR = 2;
const CUSTOMER = 3;
}
You should add in your model
namespace App;

laravel public variable for different controllers

I want to set a public variable so I can use it in different controllers. I tried this but it is not successful.
class HomeController extends Controller
{
public $TravelId;
public function __construct()
{
$this->TravelId=0;
}
}
then I used the same variable in another contorller
class HomeController extends Controller
{
public function index($cus_id)
{
//unique key for each user
$this->TravelId = $cus_id;
}
}
All your controllers extend App\Http\Controllers\Controller class by default, so you can add a property on this class and access it on all your controllers:
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
/**
* Your static property
*/
public static $travelId;
}
Then you can access it on another controller:
self::$travelId = $cus_id;

Laravel Eloquent model returns null for one to many relation

I am not sure what is going on here. I am getting returns of null despite having the info in the database.
Stimuli Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Stimuli extends Model
{
protected $table = 'stimuli';
public $timestamps = false;
/**
* Get the details associated with the stimulus
*/
public function info()
{
return $this->hasMany('App\StimuliInfo', 'attribute', 'value');
}
}
StimuliInfo Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class StimuliInfo extends Model
{
/**
* Get the stimuli associated with the detailss
*/
protected $table = 'stimuli_info';
public $timestamps = false;
public function info()
{
return $this->belongsTo(Stimuli::class);
}
}
Controller
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App;
use Illuminate\Http\Requests;
class Labels extends Controller
{
public function index()
{
}
public function objects()
{
$stimulus = App\Stimuli::with('info')->get();
foreach ($stimulus as $stim)
{
$stimuli[] = $stim->stimulus_id;
}
return $stimuli;
shuffle($stimuli);
return view('label/objects')->with(compact('stimuli'));
}
}
Okay, so here is a test controller. For some reason, I am getting a null output for every data point. Which is odd as I can see in the DB that there is data there which is not null.
I am wondering whether I am doing something fishy in the model that is not right outputting this data.
Any help would be greatly appreciated - I am at a loss for this process

one to many relationship in Laravel5 is not working properly

I have a collection controller
looks like this
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Middleware\Role;
use Illuminate\Support\Facades\Input;
use App\User;
use App\Invoice;
use Session;
use Validator;
class CollectionController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function __construct(){
$this->middleware('role:collector'); // replace 'collector' with whatever role you need.
}
public function getPayment($invoiceid){
$id =$invoiceid;
$invoice=Invoice::where('Id', $id)->with(['payments'])->get();
return View('collectionmodule/payment')->with(array('invoice'=>$invoice));
}
}
Then I have following models
Invoice
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Invoice extends Model
{
//
protected $table = 'event_invoice';
public function payments(){
return $this->hasMany('App\paymentrecieved','invoice_id');
}
public function comments(){
return $this->hasMany('App\comments','invoice_id');
}
}
Paymentrecieved
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class paymentrecieved extends Model
{
//
protected $table = 'paymentrecieved';
public function invoice(){
return $this->belongsTo('App\Invoice');
}
}
So for every Invoice there could be multiple payments .
So in My getPayment method I am writing Query like this .
$invoice=Invoice::where('Id', $id)->with(['payments'])->get();
Its getting me the Details from Invoice table . But its not getting me any Payment Details
Any one know why is this happening , According to me I have done the relationship properly
Thanks
You use Id (with uppercase) for the primary key, but the Invoice model is looking for the id (with lowercase).
You should define the primary key in the Invoice model like this:
protected $primaryKey = 'Id';

Categories