I'm learning laravel, working with 3 files, Welcome.blade.php / route.php / tryaction.php and it's a controller.
I made three links that fetched from database table => hug, greet and slap
when I click any link it gives me an error that actions is not defined.
my Welcome.blade.php:
<ul>
#foreach ($actions as $action)
<li>{{$action->name}}</li>
#endforeach
</ul>
my route.php:
<?php
Route::get('/', [
'uses' => 'tryaction#getHome',
]);
//to deal with get requests
Route::get('/{action}/{name?}', [
'uses' => 'tryaction#doget',
'as' => 'benice'
]);
my tryaction.php controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\actionstable;
class tryaction extends Controller
{
public function doget($action, $name = null){
return view('actions.'.$action,['name'=>$name]);
}
public function getHome(){
$actions = actionstable::all();
return view('welcome',['actions'=>$actions]);
}
}
when I replace the href route in welcome.blade.php with # instead of {{ route('benice', ['action' => $action->name]) }} the error stops from showing on
the data are fetched correctly and the data is shown on the page .. the problem in the route and it's that the actions is not defined, here is the error page:
Related
I tried looking for all the possible solutions none of it worked and this is very basic trying to send data from a controller to view in Laravel.
Paymentcontroller
public function payment() {
$plans =[
'Basic' => "Monthly"
];
$intent = $user->createSetupIntent();
return view('pages.subscription', compact('intent', 'plans'));
}
PageController
public function index(string $page)
{
if (view()->exists("pages.{$page}")) {
return view("pages.{$page}");
}
return abort(404);
}
View pages.subscription
<div>
{{ $intent }}
</div>
route
Route::get('{page}', ['as' => 'page.index', 'uses' => 'PageController#index']);
Route::get('/subscription', 'PaymentController#payment');
This makes the page work but doesn't display the data
Move Route::get('/subscription', 'PaymentController#payment'); before Route::get('{page}',.... (it should be your last route in the list).
Currently when you call /subscription endpoint you are calling PageController#index, but it doesn't contain logic of your PaymentController#payment and doesn't pass any data to view.
Longtime googler, first time asker here. Hi, folks.
I am debugging and updating my app after updating it from Laravel 5.1.10 to 5.6
and this bug is proving hard to google.
Exploring my error message “Trying to get property of non-object” I think what is happening is that the nested relationship path that used to work just fine to give me the object, is now instead giving me an array of its attributes.
More code below, but here is the snippet from my view:
#section('content')
<h2>
<?php // Header: project number and title ?>
#if ($bookingDefault->project->courseNumber)
{{ $bookingDefault->project->courseNumber }}:
#endif
This results in error:
Trying to get property 'courseNumber' of non-object
It’s not returning a null; the data is there and it works perfectly fine if I access the project as an array thus:
#section('content')
<h2>
<?php // Header: project number and title ?>
#if ($bookingDefault->project['courseNumber'])
{{ $bookingDefault->project['courseNumber'] }}:
#endif
So I know that the relationships are defined okay because it is finding the project. It’s just not giving a proper object to the view anymore.
I could change a large number of views to access attributes as an array instead, but that is a lot of code to comb through and change, and doesn’t give me access to the object’s methods. I would rather fix why I am getting an array instead of the object I was getting before.
CODE THAT MAY BE RELEVANT:
from app/Http/Kernel.php (partial) - I checked that SubstituteBindings::class is there.
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
from routes/web.php (partial) - all my old Route::model and Route::bind are still there. I wasn’t sure if I was supposed to take them out or put them somewhere else but fiddling with it didn’t change anything. I tried moving them to RouteServiceProvider’s boot() function but that didn’t change anything so I put them back into web.php.
Route::model('bookingdefaults', 'BookingDefault');
Route::model('bookings', 'Booking');
Route::model('people', 'User');
Route::model('projects', 'Project');
Route::bind('bookingdefaults', function($value, $route) {return App\BookingDefault::where('id', $value)->first();});
Route::bind('bookings', function($value, $route) {return App\Booking::where('id', $value)->first();});
Route::bind('people', function($value, $route) {return App\User::where('id', $value)->first();});
Route::bind('projects', function($value, $route) {return App\Project::where('id', $value)->first();});
In the models - again, not the complete code which is long:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BookingDefault extends Model
{
protected $guarded = [];
// RELATIONSHIPS
// always belongs to a certain project
public function project()
{
return $this->belongsTo('App\Project');
}
// always happens a certain place
public function location()
{
return $this->belongsTo('App\Location');
}
// many bookings could be made from this default
public function bookings()
{
return $this->hasMany('App\Booking');
}
// each booking default will suggest several roles that might be filled in a booking
public function bookingDefaultRoleAssignments()
{
return $this->hasMany('App\BookingDefaultRoleAssignment');
}
// somtimes it is defining a default of a certain type, but if this is a
// customized default then it may not belong to a bookingType
public function bookingType()
{
return $this->belongsTo('App\BookingType');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Mail;
use App\Booking;
class Project extends Model
{
protected $guarded = [];
// RELATIONSHIPS
public function bookings()
{
return $this->hasMany('App\Booking');
}
// a project can have defaults for several types of booking
public function bookingDefaults()
{
return $this->hasMany('App\BookingDefault');
}
// there will be many assignments of users to this project in various roles
public function projectRoleAssignments()
{
return $this->hasMany('App\ProjectRoleAssignment');
}
public function projectType()
{
return $this->belongsTo('App\ProjectType');
}
}
from BookingDefaultsController.php (partial - actual controller is over 1000 lines)
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\Collection;
use App\User;
use App\Booking;
use App\BookingDefault;
use App\BookingDefaultRoleAssignment;
use App\BookingRoleAssignment;
use App\BookingRole;
use App\BookingType;
use App\Location;
use App\Project;
use App\Qualification;
use Illuminate\Support\Facades\DB;
use Input;
use Redirect;
use Mail;
class BookingDefaultsController extends Controller
{
/**
* Show the form for editing the specified resource.
*/
public function edit(BookingDefault $bookingDefault)
{
// We'll need all the options for form dropdowns
$locations = Location::where('status', 'active')->orderby('location_name')->get();
$bookingTypes = BookingType::all();
$bookingRoles = BookingRole::all();
$qualifications = Qualification::all();
return view('bookingdefaults.edit',
compact('bookingDefault', 'locations', 'bookingTypes', 'bookingRoles', 'qualifications'));
}
}
And finally the view, from /resources/views/bookingdefaults/edit.blade.php
#extends('layout')
#section('title')
Staffstuff Edit Booking Default
#stop
#section('php')
{{ $user = Auth::user() }}
#stop
#section('navtag')
<div id="projpage">
#stop
#section('javascript')
#stop
#section('content')
<h2>
<?php // Header: project number and title ?>
#if ($bookingDefault->project->courseNumber)
{{ $bookingDefault->project->courseNumber }}:
#endif
#if ($bookingDefault->project->shortTitle) {{ $bookingDefault->project->shortTitle }}
#elseif ($bookingDefault->project->title) {{ $bookingDefault->project->title }}
#endif
<br />Booking Default:
</h2>
<?php // Form to edit the basic booking info, time, place ?>
{!! Form::model($bookingDefault, ['method' => 'PATCH', 'route' => ['bookingdefaults.update', $bookingDefault->id]]) !!}
{!! Form::hidden('id', $bookingDefault->id) !!}
{!! Form::hidden('project_id', $bookingDefault->project_id) !!}
#include('/partials/bookingdefaultform', ['submit_text' => 'Update Default'])
<div class="form-group">
{!! Form::label('update_existing', 'Update existing bookings (see below): ') !!}
{!! Form::checkbox('update_existing', 'value', TRUE) !!}
<br />Note that NOT updating existing bookings will decouple them from this default and they will need to be updated individually.
</div>
{!! Form::close() !!}
<p>
DONE EDITING
</p>
#stop
The exact error:
ErrorException (E_ERROR)
Trying to get property 'courseNumber' of non-object (View: /Users/redacted/Sites/testproject032418/resources/views/bookingdefaults/edit.blade.php)
This should work:
In your RouteServiceProvider (might also work in routes) change from plural to singular and add the full namespace to the 2nd argument:
Route::model('bookingdefault', App\BookingDefault::class);
// or: Route::model('bookingdefault', 'App\BookingDefault');
The rest is fine.
You'll probably need to do this for other models as well.
Edit
This is exactly what I tried on my testing project. GrandChild is just some random model I had set up:
RouteServiceProvider:
public function boot()
{
parent::boot();
Route::model('grandchild', \App\GrandChild::class);
}
Routes:
Route::resource('grandchildren', 'GrandChildController');
GrandChildController:
public function show(GrandChild $canBeWhatever)
{
return $canBeWhatever;
}
And it works:
This is code snippet from my view file.
#foreach($infolist as $info)
{{$info->prisw}} / {{$info->secsw}}
#endforeach
Here is my route which I defined inside route file
Route::get('switchinfo','SwitchinfoController');
I want to pass two values inside href tag to above route and retrieve them in controller. Can someone provide code to do this thing?
Since you are trying to pass two parameters to your controller,
You controller could look like this:
<?php namespace App\Http\Controllers;
class SwitchinfoController extends Controller{
public function switchInfo($prisw, $secsw){
//do stuffs here with $prisw and $secsw
}
}
Your router could look like this
$router->get('/switchinfo/{prisw}/{secsw}',[
'uses' => 'SwitchinfoController#switchInfo',
'as' => 'switch'
]);
Then in your Blade
#foreach($infolist as $info)
Link
#endforeach
Name your route:
Route::get('switchinfo/{parameter}', [
'as'=> 'test',
'uses'=>'SwitchinfoController#function'
]);
Pass an array with the parameters you want
<a href="{{route('test', ['parameter' => 1])}}">
{{$info->prisw}} / {{$info->secsw}}
</a>
and in controller function use
function ($parameter) {
// do stuff
}
Or if don't want to bind parameter to url and want just $_GET parameter like url/?parameter=1
You may use it like this
Route::get('switchinfo', [
'as'=> 'test',
'uses'=>'SwitchinfoController#function'
]);
function (){
Input::get('parameter');
}
Docs
You can simply pass parameter in your url like
#foreach($infolist as $info)
<a href="{{ url('switchinfo/'.$info->prisw.'/'.$info->secsw.'/') }}">
{{$info->prisw}} / {{$info->secsw}}
</a>
#endforeach
and route
Route::get('switchinfo/{prisw}/{secsw}', 'SwitchinfoController#functionname');
and function in controller
public functionname($prisw, $secsw){
// your code here
}
I am trying to display some data in a datatable in my laravel project but I encounter an error which says my data is not in the correct format I know the data is in the correct format as I have other datatables using the same data here is my controller:
<?php
namespace App\Http\Controllers;
use Datatable;
use View;
use App\Models\EC2Instance;
use App\Models\ChangedProperties;
use Illuminate\Support\Facades\Input;
use App\Models\ChangelogItem;
class ChangedPropertiesController extends Controller {
protected $layout = 'changed_properties';
public function details($changelog_item_id)
{
$changed_property = new ChangedProperties;
$changed_properties = $changed_property->where('changelog_item_id', $changelog_item_id)->get();
$table = Datatable::table()
->addColumn(
'Changed Property', 'Change Type', 'Changelog Item ID', 'Previous Value', 'Updated Value'
)
->setUrl('/changed_properties/'. $changed_properties)
->noScript();
return View::make('changed_properties')
->with('property',$changed_properties)
->with('table', $table);
}
public function instance_details($changelog_item_id)
{
$query = ChangedProperties::select(array('resource_id',
'resource_type',
'changed_property',
'change_type',
'previous_value',
'updated_value',
'changelog_item_id'
))
->get();
return Datatable::collection($query)
->showColumns(
'changed_property', 'change_type','changelog_item_id', 'previous_value', 'updated_value')
->searchColumns( 'changed_property', 'change_type', 'previous_value', 'updated_value')
->orderColumns( 'changed_property', 'change_type', 'previous_value', 'updated_value'
)
->make();
}
}
and routes:
/Homepage Route
Route::get('/', 'CRUDController#users');
// Route which populates datatable in homepage
Route::get('search', array('as' => 'instance.search', 'uses' => 'CRUDController#instances'));
//route which renders instance details
Route::get('/instance_details/{instance_id}','DetailsController#details');
//route which links to individual instance details
Route::get('/ec2_instance/{resource_type}/{resource_id}',array('as'=>'InstanceId', 'uses'=>'DetailsController#instance_details'));
//route which renders changed properties for changelog item
Route::get('/changed_properties/{changelog_item_id}/','ChangedPropertiesController#details');
//route which links to individual instance details
Route::get('/changed_properties/{changlog_item_id}/',array('as'=>'ChangelogItemId', 'uses'=>'ChangedPropertiesController#instance_details'));
Route::resource('sns', 'SNSController');
I am using Hashid to hide the id of a resource in Laravel 5.
Here is the route bind in the routes file:
Route::bind('schedule', function($value, $route)
{
$hashids = new Hashids\Hashids(env('APP_KEY'),8);
if( isset($hashids->decode($value)[0]) )
{
$id = $hashids->decode($value)[0];
return App\Schedule::findOrFail($id);
}
App::abort(404);
});
And in the model:
public function getRouteKey()
{
$hashids = new \Hashids\Hashids(env('APP_KEY'),8);
return $hashids->encode($this->getKey());
}
Now this works fine the resource displays perfectly and the ID is hashed.
BUT when I go to my create route, it 404's - if I remove App::abort(404) the create route goes to the resource 'show' view without any data...
Here is the Create route:
Route::get('schedules/create', [
'uses' => 'SchedulesController#create',
'as' => 'schedules.create'
]);
The Show route:
Route::get('schedules/{schedule}', [
'uses' => 'Schedules Controller#show',
'as' => 'schedules.show'
]);
I am also binding the model to the route:
Route::model('schedule', 'App\Schedule');
Any ideas why my create view is not showing correctly? The index view displays fine.
Turns out to solve this, I had to rearrange my crud routes.
Create needed to come before the Show route...
There's a package that does exactly what you want to do: https://github.com/balping/laravel-hashslug
Also note, that it's not a good idea to use APP_KEY as salt because it can be exposed.
Using the above package all you need to do is add a trait and typehint in controller:
class Post extends Model {
use HasHashSlug;
}
// routes/web.php
Route::resource('/posts', 'PostController');
// app/Http/Controllers/PostController.php
public function show(Post $post){
return view('post.show', compact('post'));
}