I have following code
In controller
public function ViewPost($id)
{
$viewpost= Post::find($id);
return view('Guest.viewpost', ['viewpost'=>$viewpost]);
}
In view
#foreach($viewpost as $val)
<br>
Post title=
<a href="viewpost/{{$val->id}}" >{{$val->post_title}}</a>
<br>
Post content={{$val->post_content}}
<br> <br>
Featured Image=<img src="{{$val->featured_image}}" height="150" width="150">
#endforeach
But above code throw an error Trying to get property of non-object. so i tried following way
$val['post_title'];
The above code wont throw an error nor displaying output.
If i print in controller it display output but same in view if i print it give error
print_r($viewpost);
I am using laravel 5.1. Can any one tell us what i am doing wrong ?
Thank you.
Update
after the suggestion of #CodeRomeos.i can able to display data image not loading.
<img src="{{$val->featured_image}}" height="150" width="150">
<img src="uploads/penguin.jpg">
same works in show view
Update your controller like this
public function ViewPost($id)
{
$viewpost= Post::find($id)->first();
return view('Guest.viewpost', ['viewpost'=>$viewpost]);
}
or
public function ViewPost($id)
{
$viewpost= Post::find($id)->get();
return view('Guest.viewpost', ['viewpost'=>$viewpost]);
}
Do come back if you still face the issue.!
Related
I am trying to fetch data from my admin_homes table, here is what my controller looks like:
public function index()
{
$home = AdminHome::all();
return view('admin.home.index', compact('home'));
}
I use foreach ($home as $homes) in my blade view but when I run it, I get an error saying "$home is undefined". How to solve this?
I just start to learning Laravel, I stuck in a part, I want to get data from database and pass it to a blade (view) file then use this view in another view file, and want to pass one variable to a controller but I got this error:
"Class 'adsController' not found"
web.php
Route::get('seller/panel', 'sellerController#panel');
panel.blade.php
#include('seller\hook\ads')
sellerController.php
public function panel(){
$ads = DB::table('ads')->get();
return view('hook\ads', ['ads' => $ads]);
}
adsController.php
class adsController extends Controller {
public function getStatus($p) {
if ($p == 'something') {
$status = 'yeah';
} else {
$status = 'blah blahe';
}
return view('hook\ads', $status);
}
}
ads.blade.php
<div class="ads">
#foreach ($ads as $ad)
{{ $ad->name }}
{{ adsController::getStatus($ad->approved) }}
#endforeach
</div>
So, as you see I am tring to get data from database in sellerController.php then pass it to ads.blade.php then I want to use adsController.php 's function in ads.blade.php, but it can't find adsController
Sorry I am newbie to laravel
As everyone said, it's not recommended to call the controller from the view.
Here's what I would do :
In your model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ad extends Model{
public function getStatus()
{
return $this->approved == 'something' ? 'yeah' : 'blah blaehe';
}
}
In your view :
<div class="ads">
#foreach ($ads as $ad)
{{ $ad->name }}
#include('hook.ads', ['status' => $ad->getStatus()])
#endforeach
</div>
In your controller :
public function panel(){
$ads = \App\Ad::all();
return view('hook\ads', ['ads' => $ads]);
}
At the beginning of the blade file you could include the following
#php
use App\Http\Controllers\adsController as adsController;
#endphp
then on your blade template you could use the controller as you have used here.
But it is a really bad habit to use one directly.
Since you are a newbie to Laravel change that coding practice.
You could use a service provider of a sort if you want that data which needs to be shown on a particular blade view all the time.
You should try this despite I don't recommend the approach you are trying to achieve.
{!! app('App\Http\Controllers\adsController')->getStatus($ad->approved) !!}
It should work but that's very wrong.
Most often when you get this error when your namespace declaration in the controller is wrong. Typical scenario is where you generate controller stub with Artisan and then move it somewhere else from the default location.
In some cases you need to run:
composer dumpautoload
To generate new optimized class loader map.
I am using Laravel 5.3. My first Laravel project/learning experience
In my blade file I use the following snippet to show the errors below a field after a PUT or POST request.
In this case the database field is called firstName
#if ($errors->has('firstName'))
<span class="help-block">
<strong>{{ $errors->first('firstName') }}</strong>
</span>
#endif
Now since I have lot of fields, I have keep repeatings this block for every field. I looked up the Laravel docs on Blade templates (Extending Blade section) and thought I could do the following in the AppServiceProvider class (AppServiceProvider .php)
public function boot()
{
//
Blade::directive('showIfError', function($fieldName) {
if ($errors->has('$fieldName')) {
echo "<span class='help-block'>
<strong> $errors->first('$fieldName') </strong>
</span>";
}
});
}
and then use
#showIfError('firstName')
But no luck...I get the error 'Undefined variable: errors'
Looks like the Laravel error collection is not accessible in this view file.
Appreciate any help. Thanks.
This is late reply, but hopefully it will help another person who comes along. A custom blade directive is supposed to return a string php code that will be evaluated when the template is rendered. Because the $errors variable is only available when the response is made, it won't work trying to evaluate it in the directive. The solution is this :
// custom blade directive to render the error block if input has error
// put this inside your service provider's boot method
\Blade::directive('errorBlock', function ($input) {
return
'<?php if($errors->has('.$input.')):?>
<div class=\'form-control-feedback\'>
<i class=\'icon-cancel-circle2\'></i>
</div>
<span class=\'help-block\'>
<strong><?php echo $errors->first('.$input.') ?></strong>
</span>
<?php endif;?>';
});
The thing is $errors in not accessible in closure. Also, you can't pass whole object as directive closure accepts string only. With simple data you can implode() and then explode() it, but not with an object or a collection.
What you can do is to create $errors manually inside the closure.
I've tested it and it works as expected:
Blade::directive('showIfError', function($fieldName) {
$errors = session('errors');
if ($errors->has($fieldName)) {
return "<span class='help-block'>".$errors->first($fieldName)."</span>";
}
});
The issue is that the $errors variable is only available within the views. If you take a look at the Middleware that shares the variable (https://github.com/laravel/framework/blob/5.0/src/Illuminate/View/Middleware/ShareErrorsFromSession.php) you will see that it is stored in the session.
So you can access it as follows:
$errors = session()->get('errors');
Note in your example you do have a couple of other issues; the $fieldName variable should not be in quotes. Eg:
public function boot() {
Blade::directive('showIfError', function($fieldName) {
$errors = session()->get('errors');
if ($errors->has($fieldName)) {
echo "<span class='help-block'> <strong>". $errors->first($fieldName). "</strong> </span>";
}
});
}
I finally wrote a PHP function inside my view and call it with various field names.
I hope this is a good approach. Not sure what is the best way to implement this.
function showIfError($fieldName)
{
$errors=session('errors');
if ( count( $errors)>0) {
if (session('errors')->has($fieldName)) {
$msg=$errors->first($fieldName);
echo '<span class="help-block">
<strong>'. $msg.' </strong>
</span>';
}
}
}
I have this problem in my routes where in I get this error tying to get property of non-object view (show.blade.php) on clicking a link to view/redirect allstats.blade.php. It is very weird because I am not returning my routes to show.blade.php but to allstats.blade.php. I was wondering if I am doing something wrong with the routes. This is very tricky, I don't know what's causing this error.
#Controller:
EmployeeController.php
public function postdisplaySummaryReport()
{
$employeesquery = Employee::paginate(10);
return View::make('employees.allstats')
->with('employeequerytoallstat', $employeesquery);
}
#Routes:
routes.php
Route::post('employees/sumarryReports','EmployeeController#postdisplaySummaryReport');
Route::resource('employees', 'EmployeeController');
#index.php(URL to the allstat.blade.php):
<span class="glyphicon glyphicon-folder-open"></span> {{trans('labels.payroll_reports.lbl_summary_report')}}
#ERROR:
Just change your function to this.
public function postdisplaySummaryReport()
{
$employeesquery = Employee::paginate(10);
return view('employees.allstats')
->with('employeequerytoallstat', $employeesquery);
}
also change your Route method to get instead of post if you want to display content.
Route::get('employees/sumarryReports','EmployeeController#postdisplaySummaryReport');
I have a methods that return base64 data image to a view after making a GET request to www.website.com/preview/{id}.
It is called by an <a> tag inside view.blade.php:
<a class="image-popup-vertical-fit" href="{{url(Config::get("app.previewPath") , $encrypted)}}" >
<img class="issue_img" src="{{App\Http\Classes\RepositoryUtil::getSmallImage($encrypted)}}" alt="{{ $name }}">
</a>
It work well if I declare a GET route with the code function inside routes.php:
Route::get(Config::get("app.previewPath") . "/{id}", function(\Request $request, $encrypted){
// ... some code ...
$base64 = \App\Http\Classes\RepositoryUtil::retriveImage($encrypted);
#readfile($base64);
});
But if I move the same code inside a controller's method, it return a blank page!
Route::get(Config::get("app.previewPath") . "/{id}", "MyController#getPreview");
MyController.php
public static function getPreview(\Request $request, $encrypted){
// ... same code as routes.php ...
$base64 = \App\Http\Classes\RepositoryUtil::retriveImage($encrypted);
#readfile($base64);
}
Where am I wrong?
I figure it out, it was a "distraction error".
I leave a middleware enabled in all methods of the controller, and it fails printing dd("Not authorized!"); without return before it.
It didn't return nothing without any errors!
I restrincted the middleware only to selected actions.
Thanks for support.