Cannot display the variable in the blade template from the controller - php

I cannot figure out how to display the route name in the blade template of laravel. Please find below the sample code. Thank you.
from the controller (StaffsController.php)
public function index()
{
$thisRoute = Route::current()->uri();
return view('staff.list')>with(compact('thisRoute'));
}
Blade:
{{ $thisRoute }}
This is the var_dump
/home/vagrant/Code/spark/app/Http/Controllers/StaffsController.php:20:string 'staffs' (length=6)
Error:
(1/1) UnexpectedValueException
The Response content must be a string or object implementing __toString(), "boolean" given.
When i change the code in the controller to:
public function index()
{
$thisRoute = Route::current()->uri();
return dd($thisRoute);
}
I get "staffs" as output which is correct which is a string from the dump, right?

change your return statement to be like this :
return view('staff.list', compact('thisRoute'));
if you are using laravel 5.3 or above you can get route name like this:
Route::currentRouteName();
with this, you really don't have to passe it from your controller to the view just use it directly from your blade view :
{{ Route::currentRouteName() }}

Sorry guys, I solved the issue. I missed - in the line
return view('staff.list')>with(compact('thisRoute'));
Changed it to
return view('staff.list')->with(compact('thisRoute'));
I made a mistake.
Thank you

Related

Laravel use a controller in blade

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.

Laravel 5.5 Object to update lost when passing from view to update method

I'm getting mad trying to update a simple entity, I've seen that when I change the parameter Role $role to int $id of my update method and make a findOrFail before updating, it works but it seems that my blade for::open doesn't pass my object $role to my controller.
I've tried to pass it like this in my edit blade template :
{{ Form::open(['name'=>'editrole','method'=> 'put','route'=>['Role.update',$role],
'class'=>'mt-4 ml-2']) }}
or like this :
{{ Form::open(['name'=>'editrole','method'=> 'put','url'=>route('Role.update',$role),
'class'=>'mt-4 ml-2']) }}
Here id the update method :
public function update(RoleRequest $request, Role $role)
{
try{
//dd($role);
$role->update($request->all());
return redirect(route('Role.index'))->with('success_message','Rôle modifié');
}catch (ModelNotFoundException $ex){
return redirect(route('Role.index'))->with('error_message',
'Erreur : '.$ex->getMessage().'<br />'.$ex->getTraceAsString());
}
}
when making a dd($role) in update method attributes are empty
Thanks for your help.
The route is like this :
// Gestion des rôles
Route::resource('Role','Admin\RoleController');
You cant pass the object as a route parameter. Use the id as you said, then set the object attributes in individual form fields.
You don t need the try catch because the 404 will occur before it reaches your method if the route model binding fails.
public function update(RoleRequest $request, Role $role) {
$role->update($request->all());
return redirect(route('Role.index'))->with('success_message','Rôle modifié');
}
Edit:
It's all explained in the Implicit Binding section:
https://laravel.com/docs/5.5/routing#route-model-binding

Controller to return view using variable Laravel

I have this variable that should be in my url but includes the "." (dot). Sorry I am still noob in laravel.
Expected Result is localhost/myProject/public/var_name
Eror says View [.sampleVariable] not found.
my line is
return view('/'.$create->var_name)->compact('anotherVar','anotherVar');
and my route is Route::get('{var_name}', 'MyController#index');
Route is
Route::get('/{var_name}', 'MyController#index');
MyController
public function index($var_name)
{
return view('template.index', ['var_name' => $var_name])->compact('anotherVar','anotherVar');
}
Try below code.
Your controller function code like:
public function index($var_name)
{
//Initiate your variable...
$anotherVar = '';
//Replace 'BLADEFILENAME' to you want to execute blade file name...
return view('BLADEFILENAME', compact('var_name','anotherVar'));
}
You can read more about php compact(). You can also pass variable value from controller to view by wrapping the variable in curly braces
Your route code like:
Route::get('/{var_name}', 'MyController#index');
Now you can use $var_name & $anotherVar into your blade file.

Trying to get property of non-object (show.blade.php)

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');

Symfony2 controller navbar

i would put a controller for my navbar and i would use a query to get a variable from my database..
I don't have a controller and i create it in this way:
<?php
namespace Dt\EcBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class NavbarController extends Controller {
public function navbarAction(Request $request) {
$prova = "ciao";
return $this->render('DtEcBundle:Header:navbar.html.twig',array(
"prova" => $prova,
));
}
}
Now i put my render controller in the body of : "{# app/Resources/views/base.html.twig #}"
{{ render(controller('DtEcBundle:Navbar:navbar', { 'prova': prova })) }}
I follow this but i don t understand the error: "http://symfony.com/doc/current/book/templating.html#embedding-controllers"
I Get this error Variable "prova" does not exist in DtEcBundle:Header:navbar.html.twig at line 5 but if i write the code in navbar.html.twig give me equals error..
If i remove the variable and i write only
{{ render(controller('DtEcBundle:Navbar:navbar')) }}
Give me a server error number 500 o.o..
How can i do for use my controller only in navbar.html.twig??
navbarAction doesn't take prova variable as a parameter, so why are you passing it there in a base template?
I think that action should fetch these data from db.
In that case, using:
{{ render(controller('DtEcBundle:Navbar:navbar')) }}
seems to be ok, and error is somewhere else.
If you get a 500, check logs to tell us what's exactly wrong.
And format your code, it's barely readable.
The error is the code:
{{ render(controller('DtEcBundle:Navbar:navbar', { 'prova': prova })) }}
the prova variable doesn't exists in twig, the controller is fine.
I if you want put the var from twig to controller:
/**
* #Route("/prova/{prova}", name="prova")
*/
public function navbarAction(Request $request,$prova) {
return $this->render('DtEcBundle:Header:navbar.html.twig',array(
"prova" => $prova,
));
}
and twig:
{% set prova = 'foo' %}
{{ render(controller('DtEcBundle:Navbar:navbar', { 'prova': prova })) }}

Categories