Laravel print query error - php

I have this code in routes:
Route::get('forum/{fname}/{fid}', 'viewForum#showForum');
in controller:
<?php
namespace App\Http\Controllers;
use DB;
use View;
class viewForum extends Controller
{
public function showForum($fname, $fid)
{
return View::make('forum', [
'forums' => DB::table('forums')
->where('id', $fid)
->where('seo-name', $fname)
->select()
->get()
]);
}
}
And in the layout:
#extends('layouts.main')
#section('content')
#foreach($forums as $forum)
{{ $forum->name }}
#endforeach
#stop
It's ok, but when I write bad {fname} or {fid} then nothing prints, white page, but i wan't to show error, how can I do it? I've created same with viewProfile :
<?php
namespace App\Http\Controllers;
use DB;
use View;
class viewProfile extends Controller
{
public function showProfile($uname, $uid)
{
$u = DB::table('users')
->where('id', $uid)
->where('name', $uname)
->first();
return View::make('users', [
'username' => $u->name,
'userid' => $u->id,
'email' => $u->email,
'regdate' => $u->created_at
]);
}
}
In this code error prints, but in first nope, why? How can I fix it? Thanks in advance
I'm fixed, I just added this code:
#extends('layouts.main')
#section('content')
#forelse($forums as $forum)
{{ $forum->name }}
#empty
<div class="alert alert-danger">Forum not found</div>
#endforelse
#stop

if you want to show all errors,
Set APP_ENV=local in you .env file.
Allow recursive 777 permission to /vendor and /storage folder.
It should work..
also make sure that in '/config/databse.php' file 'fetch' => PDO::FETCH_ASSOC, or 'fetch' => PDO::FETCH_CLASS, is written.
You should also see that DB::table('forums')
->where('id', $fid)
->where('seo-name', $fname)
->select()
->get();
return a 2D array, and you are required a single dimension array.
Once you be able to show errors you will find all errors easily. :)

Related

What causes the failure of this "older post" feature in my Laravel 8 app?

I am working on a blogging application in Laravel 8.
I run into a problem while trying to add a Next article and Previous article on the single article view.
In the ArticlesController controller I have this method to display a single article:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\ArticleCategory;
use App\Models\Article;
use App\Models\Comment;
class ArticlesController extends FrontendController {
// More code
public function show($slug) {
// Single article
$article = Article::firstWhere('slug', $slug);
$old_article = Article::firstWhere('id', '<', $article->id);
$new_article = Article::firstWhere('id', '>', $article->id);
$comments = Comment::where('article_id', $article->id)->orderBy('id', 'desc')->get();
return view('themes/' . $this->theme_directory . '/templates/single',
array_merge($this->data, [
'categories' => $this->article_categories,
'article' => $article,
'old_article' => $old_article,
'new_article' => $new_article,
'comments' => $comments,
'tagline' => $article->title,
])
);
}
}
In the Blade view:
#if($old_article)
<div class="next-nav">
<a href="{{ url('/show/' . $old_article->slug) }}">
<span>Older</span>
{{ $old_article->title }} {{ $old_article->id }}
</a>
</div>
#endif
#if($new_article)
<div class="next-nav">
<a href="{{ url('/show/' . $new_article->slug) }}">
<span>Newer</span>
{{ $new_article->title }} {{ $new_article->id }}
</a>
</div>
#endif
The problem
For a reason I was unable to understand, the link to an older post does not work.
The line {{ $old_article->id }} always returns 1.
Questions
What causes this bug?
What is the easiest fix?
If your $article has an ID of, let's say 10, then all Article records with an ID of 1 - 9 are "Older". You need to order your query so it gets the closest "Old" Article:
$article = Article::where('slug', $slug)->firstOrFail();
$oldArticle = Article::where('id', '<', $article->id)->orderBy('id', 'DESC')->first();
$newArticle = Article::where('id', '>', $article->id)->orderBy('id', 'ASC')->first();
Your "New" Article query was fine, default order is id, ASC, but for clarity, it doesn't hurt to make it consistent.

Undefined variable: names in Laravel 5.6 app?

I am going to count some table column values using following controller function,
public function showcategoryname()
{
$names = Vehicle::groupBy('categoryname')->select('id', 'categoryname', \DB::raw('COUNT(*) as cnt'))->get();
return view('_includes.nav.usermenu')->withNames($names);
}
then my route is,
Route::get('_includes.nav.usermenu', [
'uses' => 'VehicleController#showcategoryname',
'as' => '_includes.nav.usermenu',
]);
and my usermenu blade file is include with other blade files like this,
div class="col-md-3 ">
#include('_includes.nav.usermenu')
</div>
and usermenu blade view is,
#foreach($names as $name)
{{ $name->categoryname }} ({{ $name->cnt }})
#endforeach
in my url like this
http://localhost:8000/_includes.nav.usermenu
this is working fine. but when i visit other pages include usermenu blade it is generated following error,
Undefined variable: names (View: C:\Users\banda\Desktop\dddd\resources\views\_includes\nav\usermenu.blade.php) (View: C:\Users\banda\Desktop\dddd\resources\views\_includes\nav\usermenu.blade.php)
how can fix this problem?
it's clear that you are just using showcategoryname() method in _includes.nav.usermenu route not in every routes so it can't recognize that variable, it's better to use a global variable in all routes
so in app\Providers\AppServiceProviders.php in boot function use this code to have that variable in all routes:
view()->composer('*', function ($view) {
$names = Vehicle::groupBy('categoryname')->select('id', 'categoryname', \DB::raw('COUNT(*) as cnt'))->get();
$view->with('names', $names);
});
this code runs before any code or controller! actually is feature of boot function!
You can insert this code into boot function in App\Providers\AppServiceProvider class
public function boot(){
$names = Vehicle::groupBy('categoryname')->select('id', 'categoryname', \DB::raw('COUNT(*) as cnt'))->get();
View::share('names', $names);
}

Laravel 5.6, relationship path is returning array instead of object

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:

Laravel - route within view isn't working

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:

Laravel some questions (pagination, if - foreach)

I'm laravel newbie. I'm created simple code and I have some questions:
I think this code bad (it works, but I use #forelse($forums as $forum) and anywhere use $forum)
#extends('layouts.main')
#section('content')
#forelse($forums as $forum) <-- I don't like this line, it works but i think it's possible with if or something else
#forelse($topics as $topic)
{{ $topic->title }}<br>
#empty
Sorry but this forums empty.
#endforelse
#empty
Sorry but this forum not found
#endforelse
#stop
And second question how to make pagination? I'm tried this:
<?php
namespace App\Http\Controllers;
use DB;
use View;
class viewForum extends Controller
{
public function showForum($fname, $fid)
{
return View::make('forum', [
'forums' => DB::table('forums')
->where('id', $fid)
->where('seo_name', $fname)
->select()
->get()
->simplePagination(5)
]);
}
}
But not work's, I'm tried tutorials..etc, how to? Thanks so much in advance ! :)
for your first question. You can use #foreach or #each. these are the two that i usually used.
for your second question:
return View::make('forum', [
'forums' => DB::table('forums')
->where('id', $fid)
->where('seo_name', $fname)
->select()
->paginate(5);
]);
remove ->get()
and replace simplePagination(5) with paginate(5)
documation http://laravel.com/docs/5.0/pagination
Update
change you code block from
return View::make('forum', [
'forums' => DB::table('forums')
->where('id', $fid)
->where('seo_name', $fname)
->select()
->paginate(5);
]);
to
$forums = DB::table('forums')
->where('id', $fid)
->where('seo_name', $fname)
->select()
->paginate(5);
return View::make('forum', compact('forums'));
then check if $forums->render() got error.
Update
$forums = DB::table('forums')
->where('id', $fid)
->where('seo_name', $fname)
->select()
->get(5);
$topics = DB::table('topics')
->where('forum_id', $id)
->select()
->paginate(2)
return View::make('forums', compact('forums', 'topics'));
on your view you do <?php echo $topics->render() ?> since topic is the one you paginate. also you can remove ->select() from your code. if you don't specify fields to output.
For #foreach ($topics as $topic)
{{$topic->title}}
#endforeach
For Pagination
$users = User::where('status','1')
->paginate(10);
Note: In View add this {{$user->links()}} for getting the pagination links.
you can use #foreach() #endforeach and probably #if #else #endif
see sample:
#foreach($forums as $forum)
#if($forum==0)
{{'empty'}}
#else
{{ 'Not empty' }}
#endif
#endforeach
for pagination i will suggest you use jquery datatable for proper pagination. Its quite okay and saves lots of time. see below the sample implementation:
//this preload the jquery library for datatable together with the print button
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.print.min.js"></script>
//this section call the document ready event making sure that datatable is loaded
<script>
$(document).ready(function() {
$('#').DataTable();
} );
//this section display the datatable
$(document).ready(function() {
$('#mytable').DataTable( {
dom: 'Bfrtip',
"pageLength": 5, //here you can set the page row limit
buttons: [
{
extend: 'print',
customize: function ( win ) {
$(win.document.body)
.css( 'font-size', '10pt' )
.prepend(
''
);
$(win.document.body).find( 'table' )
.addClass( 'compact' )
.css( 'font-size', 'inherit' );
}
}
]
} );
} );
</script>
//you can display record on the datatable as shown below
<div class="table-responsive col-md-12">
<table id="mytable" class="table table-bordered table-striped table-highlight">
<thead>
<tr bgcolor="#c7c7c7">
<th>S/N</th>
<th>Name</th>
</tr>
</thead>
<tbody>
#php
$i=1;
#endphp
#foreach($queryrecord as $list)
<tr>
<td>{{ $i++ }}</td>
<td>{{ $list->name }}</td>
</tr>
#endforeach
</tbody>
</table>
<hr />
</div>
Note: remember before displaying information on the datatable, you must have query your record from database.i'm using query builder here as sample
$data['queryrecord']=DB::table('tablename')->get();

Categories