Laravel PHP: Creating default object from empty value error - php

I'm using a controller to call up a form defined in one of my views. Within the controller, I have a simple 'create()' method that I just want to use to call up a form while using the 'Video' model I've defined. The problem is when I try to call this function, I keep getting a 'Creating default object from empty value' error.
Controller(app\VideosController.php):
<?php
use Acme\repositories\VideoRepository;
use Models\Video;
use Models\Validators as Validators;
class VideosController extends BaseController {
/**
* The video model
*
* #var \Models\Video
**/
protected $video;
/* The value defined from my repository
*/
protected $videoRepo;
/**
* Instantiate the controller
*
* #param Models\Video $video
* #return void
**/
public function __construct(VideoRepository $videoRepo)
{
$this->videoRepo = $videoRepo;
/* Old code below
$this->video = \App::make('Repositories\VideoRepository');
*/
}
/* Create a new video by passing in a sub view
Of the form for creating a new video */
public function create()
{
$data = array('type' => 'video');
$this->layout->content = \View::make('forms.new-video', $data);
}
}
Model(app/models/video.php):
<?php
class Video extends Eloquent {
/**
* The table used by this model
*
* #var string
**/
protected $table = 'videos';
/**
* The primary key
*
* #var string
**/
protected $primaryKey = 'video_id';
/**
* The fields that are guarded cannot be mass assigned
*
* #var array
**/
protected $guarded = array();
/**
* Enabling soft deleting
*
* #var boolean
**/
protected $softDelete = true;
}
The view for my form is located at 'app\views\forms\new-video.blade.php'.
Am I not defining my 'create()' method properly or is a matter of not placing files in their correct location?

I believe you are missing the declaration of the $layout property in your controller, so it has no idea what view to use as the template:
/**
* The layout that should be used for responses.
*/
protected $layout = 'layouts.master';
See http://laravel.com/docs/4.2/templates#controller-layouts.

Related

Laravel model pass to view

Im using this library: https://www.laravelplay.com/packages/ycs77::laravel-wizard
I did all steps and have the same result like in the example.
Im trying to get data from database to each step.
Model (App/steps/intro/DropboxStep.php):
<?php
namespace App\Steps\Intro;
use Illuminate\Http\Request;
use Ycs77\LaravelWizard\Step;
use DB;
class DropboxStep extends Step
{
/**
* The step slug.
*
* #var string
*/
protected $slug = 'dropbox';
/**
* The step show label text.
*
* #var string
*/
protected $label = 'Dropbox';
/**
* The step form view path.
*
* #var string
*/
protected $view = 'steps.intro.dropbox';
/**
* Set the step model instance or the relationships instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Relations\Relation|null
*/
public function model(Request $request)
{
//
}
/**
* Save this step form data.
*
* #param \Illuminate\Http\Request $request
* #param array|null $data
* #param \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Relations\Relation|null $model
* #return void
*/
public function saveData(Request $request, $data = null, $model = null)
{
//
}
/**
* Validation rules.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function rules(Request $request)
{
return [];
}
public function getOptions()
{
$stepa2 = DB::table('tutorials')->where('id', '2')->first();
return [
'stepa2' => $stepa2,
'Lucas',
];
}
}
View:
<div class="form-group">
{{ $stepa2 }}
</div>
Result:
Undefined variable: stepa2
Tried also through controller (IntroWizardController.php)
This is default controller:
<?php
namespace App\Http\Controllers;
use App\Steps\Intro\DropboxStep;
use App\Steps\Intro\H2NStep;
use App\Steps\Intro\PT4Step;
use Ycs77\LaravelWizard\Wizardable;
use DB;
class IntroWizardController extends Controller
{
use Wizardable;
/**
* The wizard name.
*
* #var string
*/
protected $wizardName = 'intro';
/**
* The wizard title.
*
* #var string
*/
protected $wizardTitle = 'Intro';
/**
* The wizard options.
*
* #var array
*/
protected $wizardOptions = [];
/**
* The wizard steps instance.
*
* #var array
*/
protected $steps = [
DropboxStep::class,
H2NStep::class,
PT4Step::class,
];
}
I added:
public function getOptions()
{
$stepa2 = DB::table('tutorials')->where('id', '2')->first();
return [
'stepa2' => $stepa2,
'Lucas',
];
}
Tried also in controller return to view, but then I get result from database in blank page, not with other parts.
Is it possible to pass database query to view with this library?
Thanks
EDIT:
With this routes:
Route::get('wizard/intro/dropbox', 'IntroWizardController#step1a', 'wizard.intro.dropbox');
Wizard::routes('wizard/intro', 'IntroWizardController', 'wizard.intro');
I get my result from database, but like I said before in white blank page:
But I want to get in this view like others (without query):
To pass any data from controller to blade view simply use these 2 options
option 1:
public function someFunction()
{
$model = DB::table('model_table')->where('id', '2')->first();
return view('blade_view_name', compact('model'));
}
option 2:
public function someFunction()
{
$model = DB::table('model_table')->where('id', '2')->first();
return view('blade_view_name')->with('model', $model);
}
if you have more or want more of variables you can chain the with() method like this:
return view('blade_view_name')
->with('model', $model)
->with('variable', 'Some other variable');

PhpDOC syntax for related table

PHPStorm complains about a property accessed via magic method, because I didn't set the related comment:
<?php
namespace App\Controller;
use App\Model\Entity\ItemOrder;
use Cake\Datasource\Exception\RecordNotFoundException;
use Cake\Datasource\ResultSetInterface;
use Cake\Http\Response;
use Cake\Network\Exception\NotFoundException;
/**
* Items Controller
*
* #property ItemsTable $Items
*
* #method Item[]|ResultSetInterface paginate($object = null, array $settings = [])
*/
class ItemOrdersController extends AppController
{
/**
* Index method
*
* #return Response|void
*/
public function index()
{
$this->paginate = [
'contain' => ['Orders', 'ItemOrdersTypes', 'Products', 'ItemOrdersStates', 'Proformas', 'DeliveryNotes', 'Invoices']
];
$itemOrders = $this->paginate($this->Items);
$this->set(compact('itemOrders'));
}
/**
* Add method
* #param string $id Item id.
* #return Response|null Redirects on successful add, renders view otherwise.
*/
public function add($id)
{
$itemOrder = $this->ItemOrders->newEntity(); // <--- this one
// ...
}
}
I'm not sure what is the right syntax to declare such a property.
I tried with
* #property ItemOrders $ItemOrders
and
* #property ItemOrdersTable $ItemOrders
and
* #property object $ItemOrders
but without luck.
I also checked the docs for property and type without finding nothing useful.

Laravel Nova 404 when using hasMany

In my Laravel Nova project, I have a Page and a PageTranslation (model and resource). When adding a hasMany to my Resource fields, upon visiting the detail of the Page, I get a 404 error. This is my code
This is my Page Resource
<?php
namespace App\Pages\Resources;
use Illuminate\Http\Request;
use Laravel\Nova\Resource;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Fields\HasMany;
class Page extends Resource
{
/**
* The model the resource corresponds to.
*
* #var string
*/
public static $model = 'App\Pages\Models\Page';
/**
* The single value that should be used to represent the resource when being displayed.
*
* #var string
*/
public static $title = 'working_title';
/**
* #var string
*/
public static $group = 'Pages';
/**
* The columns that should be searched.
*
* #var array
*/
public static $search = [
'id', 'working_title'
];
/**
* Eager load translations
*/
public static $with = ['translations'];
/**
* Get the fields displayed by the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Text::make('Title', 'working_title')
->sortable()
->rules('required', 'max:256'),
HasMany::make('Translations', 'translations', \App\Pages\Resources\PageTranslation::class)
];
}
}
This is my PageTranslation Resource
<?php
namespace Codedor\Pages\Resources;
use Illuminate\Http\Request;
use Laravel\Nova\Resource;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;
class PageTranslation extends Resource
{
/**
* The model the resource corresponds to.
*
* #var string
*/
public static $model = 'Codedor\Pages\Models\PageTranslation';
/**
* Hide resource from Nova's standard menu.
* #var bool
*/
public static $displayInNavigation = false;
/**
* Get the fields displayed by the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Text::make('Locale')
->sortable()
->rules('required', 'max:256')
];
}
}
I'm a little bit late, but if anyone comes across this issue while using Nova::resources instead of the resources path inside resources method in NovaServiceProvider, make sure you add the related resource to the list.
If you wish to hide a resource from the sidebar navirgation, just use public static $displayInNavigation = false; inside the resource file
It's not related to relationships at all. Make sure you've included the resources in your NovaServiceProvider
Also, to restrict from viewing in the sidebar based on user role, you can do something like:
public static function availableForNavigation(Request $request)
{
return $request->user()->isAdmin();
}

In Laravel 5.3 Eloquent how to retrieve 3rd table data with where condition

I have 3 Models(each associated with a table separately) which associated with each other I have attached the table structure below
Models are,
Doctor Model associated with doctor_profile_master
<?php
namespace App\TblModels;
use Illuminate\Database\Eloquent\Model;
class Doctor extends Model
{
/**
* #var string
*/
protected $table = 'DOCTOR_PROFILE_MASTER';
/**
* #var string
*/
protected $primaryKey = 'doctor_profile_master_id';
/**
* #var array
*/
protected $fillable = ['doctor_id', 'user_master_id', 'doctor_first_name', 'doctor_last_name', 'doctor_isactive'];
/**
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function hospitalDoctorAssociateMasters(){
return $this->hasMany('App\TblModels\HospitalDoctorAssociateMaster','doctor_profile_master_id');
}
}
HospitalDoctorAssociateMaster Model associated with hospital_doctor_associate_master
<?php
namespace App\TblModels;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
class HospitalDoctorAssociateMaster extends Model
{
/**
* #var string
*/
protected $table = 'HOSPITAL_DOCTOR_ASSOCIATE_MASTER';
/**
* #var string
*/
protected $primaryKey = 'hospital_doctor_associate_master_id';
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function doctor(){
return $this->belongsTo('App\TblModels\Doctor','doctor_profile_master_id');
}
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function hospital(){
return $this->belongsTo('App\TblModels\Hospital','hospital_profile_master_id');
}
}
HospitalDoctorRecurringSchedule Model associated with hospital_doctor_recurring_schedule
<?php
namespace App\TblModels;
use Illuminate\Database\Eloquent\Model;
class HospitalDoctorRecurringSchedule extends Model
{
/**
* #var string
*/
protected $table = 'HOSPITAL_DOCTOR_RECURRING_SCH_MASTER';
/**
* #var string
*/
protected $primaryKey = 'hospital_doctor_recurring_sch_master_id';
public function hospitalDoctorAssociateMaster(){
return $this->belongsTo('App\TblModels\HospitalDoctorAssociateMaster','hospital_doctor_associate_master_id');
}
}
Thing i want to do is,
How to retrieve the hospital_doctor_recurring_sch_master table data using specific doctor_id(doctor_profile_master)
I tried some methods but cant able to retrieve those values.
Thanks in advance.
You could use something like this:
$hospitalDoctors = HospitalDoctorRecurringSchedule::with(['hospitalDoctorAssociateMaster', 'hospitalDoctorAssociateMaster.doctor', 'hospitalDoctorAssociateMaster.hospital'])->all();
To search by fields in related tables:
$hospitalDoctors = HospitalDoctorRecurringSchedule::with([
'hospitalDoctorAssociateMaster',
'hospitalDoctorAssociateMaster.doctor',
'hospitalDoctorAssociateMaster.hospital'])
->whereHas('hospitalDoctorAssociateMaster.doctor', function ($query) use ($doctorId) {
$query->where('doctor_id', '=', $doctorId);
})
->all();
For hospitalDoctorAssociateMaster.hospital:
Define Hospital Model and try

laravel 4 pivot table save not working

I am having trouble saving(creating new row) with extra data to a pivot table.
I am having to use a legacy db schema (that is still working on a live site). I am currently redoing the site in Laravel.
<?php namespace Carepilot\Repositories\Organizations;
use Carepilot\Repositories\EloquentRepositoryAbstract;
/*
* This class is the Eloquent Implementation of the Organization Repository
*/
class OrganizationRepositoryEloquent extends EloquentRepositoryAbstract implements OrganizationRepositoryInterface {
/*
* Define Eloquent Organization Type Relation.
*
*/
public function orgtypes()
{
return $this->belongsToMany('Carepilot\Repositories\OrganizationTypes\OrganizationTypesRepositoryEloquent', 'organizations_orgtypes', 'organization_id', 'orgtype_id')
->withPivot('objectstate_id');
}
}
<?php namespace Carepilot\Repositories\OrganizationTypes;
use Carepilot\Repositories\EloquentRepositoryAbstract;
/*
* This class is the Eloquent Implementation of the Organization Repository
*/
class OrganizationTypesRepositoryEloquent extends EloquentRepositoryAbstract implements OrganizationTypesRepositoryInterface {
protected $table = 'orgtypes';
/*
* Define Eloquent Organization Type Relation.
*
*/
public function organizations()
{
return $this->belongsToMany('Carepilot\Repositories\Organizations\OrganizationRepositoryEloquent', 'organizations_orgtypes', 'organization_id', 'orgtype_id')
->withPivot('objectstate_id');
}
}
Here in the Orgaizations controller I try to save a new organization but get an error in the pivot table.
<?php
use \Carepilot\Repositories\Organizations\OrganizationRepositoryInterface;
use \Carepilot\Repositories\Procedures\ProcedureRepositoryInterface;
use \Carepilot\Helpers\StatesHelper;
class OrganizationsController extends BaseController {
/**
* Organization Repository
*
* #var organization_repo
*/
protected $organization_repo;
protected $procedures;
protected $states;
public function __construct(OrganizationRepositoryInterface $organization_repo,
ProcedureRepositoryInterface $procedures,
StatesHelper $states)
{
$this->organization_repo = $organization_repo;
$this->procedures = $procedures;
$this->states = $states;
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
return View::make('organizations.index');
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
$supportedStates = ['' => 'Choose'] + $this->states->supportedStates();
$procedures = $this->procedures->getDropDown();
return View::make('organizations.create', compact('supportedStates', 'procedures'));
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$input = Input::all();
// validation here
$new_organization = $this->organization_repo->create(array_only($input, ['organization_name']));
$input['objectstate_id'] = 27;
$input['orgtype_id'] = 1;
$new_organization->orgtypes->pivot->create(array_only($input, ['objectstate_id', 'orgtype_id']));
$new_organization->addresses()->create(array_only($input, ['street1', 'zip', 'city', 'state_code']));
$input['objectstate_id'] = 4;
$new_organization->users()->create(array_only($input, ['first_name', 'last_name', 'email', 'password', 'objectstate_id']));
return "completed";
}
This returns "Undefined property: Illuminate\Database\Eloquent\Collection::$pivot” because the pivot has not been created yet. What am I missing?
I found that the 'attach' method does what I want with something like
$new_organization->orgtypes()->attach(1, ['objectstate_id' => '27']);

Categories