Laravel breadcrumbs bundle cannot find custom template - laravel

I am using https://github.com/davejamesmiller/laravel-breadcrumbs package.
Installed as it says in instructions, but i want to create a custom template for my breadcrumbs.
I have created app/breadcrumbs.php:
Breadcrumbs::register('home', function($breadcrumbs) {
$breadcrumbs->push('Home', route('home'));
});
Breadcrumbs::register('about', function($breadcrumbs) {
$breadcrumbs->parent('home');
$breadcrumbs->push('About company', route('about'));
});
Then in config file of that package:
return array(
'view' => 'laravel-breadcrumbs::_partials.breadcrumbs',
);
Then created that view in app/views/_partials/breadcrumbs.blade.php:
#if ($breadcrumbs)
<ul class="breadcrumb">
#foreach ($breadcrumbs as $breadcrumb)
#if (!$breadcrumb->last)
<li>{{{ $breadcrumb->title }}}</li>
#else
<li class="active">{{{ $breadcrumb->title }}}</li>
#endif
#endforeach
</ul>
#endif
Then i am printing that breadcrumb in my view:
{{ Breadcrumbs::render('about') }}
However, i am getting error:
View [_partials.breadcrumbs] not found.
How it cannot be found if i created it?!? spent 4 hours to figure out that thing. Please. help

James helped me. I had to do:
return array(
'view' => '_partials.breadcrumbs',
);

Related

Laravel - ERROR: Trying to get property 'depthead' of non-object

In my Laravel-5.8 blade that has this code:
#foreach($employees as $key => $employee)
<li class="list-group-item">
<b>Line Manager:</b>
#if(!$employee->linemanager)
<a class="float-right">N/A</a>
#else
<a class="float-right">{{ $employee->linemanager->fullName() ?? 'None' }}</a>
#endif
</li>
<li class="list-group-item">
<b>HOD:</b>
#if(!$employee->department->depthead)
<a class="float-right">N/A</a>
#else
<a class="float-right">{{isset($employee->department->depthead) ? $employee->department->depthead->first_name. ' ' .$employee->department->depthead->last_name : 'None'}}</a>
#endif
</li>
#endforeach
and its pointing to this line:
#if(!$employee->department->depthead)
How do I resolve it?
Thanks
The root cause of your issue is that $employee->department is either null or not an Object (Instance of Department, assuming you have Model and Relationships setup properly). You've got a check in place, but it's in the wrong spot. Check for $employee->department and $employee->department->depthead:
#if($employee->department)
#if($employee->department->depthead)
{{ $employee->department->depthead->first_name. ' ' .$employee->department->depthead->last_name }}
#else
None
#endif
#else
N/A
#endif
The defaults returned from a properly formed relationship will remove the need for string checks, meaning that #if($employee->department) and #if($employee->department->depthead) will be "truthy" or "falsey" enough to handle your use case.
Sidenote, this complexity is best moved to a Model function. In your Employee model, add this function:
public function getDepartmentHeadAttribute(){
if ($this->department) {
if ($this->department->depthead) {
return "{$this->department->depthead->first_name} {$this->department->depthead->last_name}";
} else {
return 'None';
}
} else {
return 'N/A';
}
}
Then, in your .blade.php file, you can simply do:
#foreach($employees as $employee)
{{ $employee->department_head }}
#endforeach
And it will perform the required if checks inside your Model and output First/Last, None or N/A as requird.
#if(!$employee->department->depthead)
look like the employee->department is not null, but it is not an object too ...
may be it is a string or number ....
#if(!$employee->department->depthead)
you could use 'is_object' method to determine that ...
#if( is_object($employee->department))
#if(!$employee->department->depthead)
....
#endIf
#endIf
but i don't think that the problem ...
the problem maybe you miss loading the relation,
if the property 'department' is a field of type 'json'
don't forget to cast it in model to 'array'

Homepage won't show newly added records but other pages do

I'm using a Laravel 5.7 in an old web project last year 2019 but now I encountered a very weird bug.
This is a website that when you add a new game, it will show to the menu list and if it is featured it will show to the homepage content.
this is the table ['game_id', 'name', 'key', 'status', 'order', 'is_featured']
in the header view I put this code:
<ul class="nav-menu">
<li class="{{ ($page == "games" ? 'menu-active' : '') }} submenu dropdown"><a href="/games" >Games</a>
<ul class="dropdown-menu">
#foreach(GetPublishedGames() as $game)
<li class="nav-item">{{$game->name}}</li>
#endforeach
</ul>
</li>
...
calling this helper code GetPublishedGames()
function GetPublishedGames(){
$data = DB::table("game")->where("status", 1)->orderBy("order")->get();
return $data;
}
in the homepage controller I had this line
"feat_games" => Game::where("status", 1)->where("is_featured", 1)->orderBy("order")->limit(5)->get(),
that calls in the homepage view:
#if(count($feat_games))
#foreach($feat_games as $feat_game)
<div class="feat-game-item wow fadeInUp">
... some content ...
</div>
#endforeach
#endif
I have no idea why this happening, it works before in the local and development stage. I did tried to clear cache.
any idea?

Laravel best way to call a controller inside a view?

I have a page who contains children blocs.
Each blocs need to have a specific render (with specific template).
For this i had to use #php in my blade template.
This is my code :
PageController.php
public function edit(Page $page)
{
return view('pages.edit', compact('page'));
}
View page/edit.blade.php
<section id="contents" class="contents ui-sortable">
#foreach ($page->blocs as $bloc)
#php
echo $bloc->id;
echo App\Http\Controllers\BlocController::renderBloc($bloc);
#endphp
#endforeach
</section>
BlocController.php
public static function renderBloc(Bloc $bloc) {
echo $bloc->id;
return view('blocs.show.' . $bloc->bloc_type, [
'bloc' => $bloc,
'data' => json_decode($bloc->data)
]);
}
And then an exemple of bloc
resources/views/blocs/show/text.blade.php
#extends('blocs.show')
#section('bloc')
{{ $bloc->id }}
#endsection
resources/views/blocs/show.blade.php
<section class="bloc bloc_{{ $bloc->bloc_type }}" data-bid="{{ $bloc->id }}">
{{$bloc->id}}
#yield('bloc')
</section>
I have 2 problems with this :
I think it's not really a good way to do ? I don't like to use #php in template. I would love to have an opinion about this ? Maybe i need to use a Service Provider ?
The $bloc->id inside the template (resources/views/blocs/show/text.blade.php) is wrong (it shows the id of the first child bloc in the foreach, even if all my echo $bloc->id before display the good id (page/edit/blade.php, BlocController.php, resources/view/blocs/show.blade.php). This is an other proof i'm doing something wrong i guess ?
Thanks
If you have to use controller in your views, it means only that you have not so good architecture. Laravel's Blade easily can do what you try to solve via controller.
You can use #include with parameters and get rid of #php:
resources/views/pages/edit.blade.php
#foreach ($page->blocs as $bloc)
#include('blocs.show', ['bloc' => $bloc])
#endforeach
resources/views/blocs/show.blade.php
<section class="bloc bloc_{{ $bloc->bloc_type }}" data-bid="{{ $bloc->id }}">
{{$bloc->id}}
#include('blocs.show.' . $bloc->bloc_type, [
'bloc' => $bloc,
'data' => json_decode($bloc->data)
])
</section>
resources/views/blocs/show/text.blade.php
Bloc ID = {{ $bloc->id }}
Bloc Text = {{ $data->text }}

Laravel - global navigation

I have a navigation section built from a loop of my companies model.
So the nav looks like this
#foreach ($companies as $company)
{{ link_to("company/{$company->id}/users", $company->name, ['class' => 'btn btn-xs btn-primary']) }}
#endforeach
This grabs all of the company names and id's to build the button links for each company.
this works fine on my companies view, but I also want to include this in the main layout navigation.
What is the best why to do this? I was thinking to add a function to the base controller but not sure how or what view to return?
Create a file, you can name something like views/partials/companies.blade.php and add your foreach in it:
#foreach ($companies as $company)
{{ link_to("company/{$company->id}/users", $company->name, ['class' => 'btn btn-xs btn-primary']) }}
#endforeach
Then, everywhere you need it, you just have to tell Blade to include that partial:
#include('partials.companies')
Having your data globally available for this partial would require a View Composer:
View::composer(array('your.first.view','your.second.view'), function($view)
{
$view->with('companies', Company::all());
});
You can create a file to store your composers, something like app/composers.php and load it in your app/start/global.php:
require app_path().'/composers.php';

Laravel Redirect Back with() Message

I am trying to redirect to the previous page with a message when there is a fatal error.
App::fatal(function($exception)
{
return Redirect::back()->with('msg', 'The Message');
}
In the view trying to access the msg with
Sessions::get('msg')
But nothing is getting rendered, am I doing something wrong here?
Try
return Redirect::back()->withErrors(['msg' => 'The Message']);
and inside your view call this
#if($errors->any())
<h4>{{$errors->first()}}</h4>
#endif
Laravel 5 and later
Controller
return redirect()->back()->with('success', 'your message,here');
Blade:
#if (\Session::has('success'))
<div class="alert alert-success">
<ul>
<li>{!! \Session::get('success') !!}</li>
</ul>
</div>
#endif
Alternative approach would be
Controller
use Session;
Session::flash('message', "Special message goes here");
return Redirect::back();
View
#if (Session::has('message'))
<div class="alert alert-info">{{ Session::get('message') }}</div>
#endif
In Laravel 5.4 the following worked for me:
return back()->withErrors(['field_name' => ['Your custom message here.']]);
You have an error (misspelling):
Sessions::get('msg')// an extra 's' on end
Should be:
Session::get('msg')
I think, now it should work, it does for me.
Just set the flash message and redirect to back from your controller functiion.
session()->flash('msg', 'Successfully done the operation.');
return redirect()->back();
And then you can get the message in the view blade file.
{!! Session::has('msg') ? Session::get("msg") : '' !!}
In Laravel 5.5:
return back()->withErrors($arrayWithErrors);
In the view using Blade:
#if($errors->has())
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
In laravel 5.8 you can do the following:
return redirect()->back()->withErrors(['name' => 'The name is required']);
and in blade:
#error('name')
<p>{{ $message }}</p>
#enderror
For Laravel 5.5+
Controller:
return redirect()->back()->with('success', 'your message here');
Blade:
#if (Session::has('success'))
<div class="alert alert-success">
<ul>
<li>{{ Session::get('success') }}</li>
</ul>
</div>
#endif
in controller
For example
return redirect('login')->with('message',$message);
in blade file
The message will store in session not in variable.
For example
#if(session('message'))
{{ session('message') }}
#endif
I stopped writing this myself for laravel in favor of the Laracasts package that handles it all for you. It is really easy to use and keeps your code clean. There is even a laracast that covers how to use it. All you have to do:
Pull in the package through Composer.
"require": {
"laracasts/flash": "~1.0"
}
Include the service provider within app/config/app.php.
'providers' => [
'Laracasts\Flash\FlashServiceProvider'
];
Add a facade alias to this same file at the bottom:
'aliases' => [
'Flash' => 'Laracasts\Flash\Flash'
];
Pull the HTML into the view:
#include('flash::message')
There is a close button on the right of the message. This relies on jQuery so make sure that is added before your bootstrap.
optional changes:
If you aren't using bootstrap or want to skip the include of the flash message and write the code yourself:
#if (Session::has('flash_notification.message'))
<div class="{{ Session::get('flash_notification.level') }}">
{{ Session::get('flash_notification.message') }}
</div>
#endif
If you would like to view the HTML pulled in by #include('flash::message'), you can find it in vendor/laracasts/flash/src/views/message.blade.php.
If you need to modify the partials do:
php artisan view:publish laracasts/flash
The two package views will now be located in the `app/views/packages/laracasts/flash/' directory.
Here is the 100% solution
*Above mentioned solutions does not works for me but this one works for me in laravel 5.8:
$status = 'Successfully Done';
return back()->with(['status' => $status]);
and receive it as:
#if(session()->has('status'))
<p class="alert alert-success">{{session('status')}}</p>
#endif
It works for me and Laravel version is ^7.0
on Controller
return back()->with('success', 'Succesfully Added');
on Blade file
#if (session('success'))
<div class="alert alert-success">
{!! session('success') !!}
</div>
#endif
For documentation look at Laravel doc
I know this is an old post but this answer might help somebody out there.
In Laravel 8.x this is what worked for me: You can return the error to the previous page or to another page.
return Redirect::back()->withErrors(['password' => ['Invalid Username or Password']]);
This will also work:
return view('auth.login')->withErrors(['username' => ['Invalid Username or Password']]);
Please ENSURE, however, that the page/view you are returning has a field name that corresponds to the first parameter passed in the withErrors method (in this case, username or password) and that the #error directive in your view references the same field like this
#error('password') //or #error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
for example
Hope this helps somebody. Cheers.
#Laravel-9
Inside the blade where this redirection back action initiated
return redirect()->back()->with('message', "The Message");
Inside the blade where this form, will be returned after the above action
#if(session()->has('message'))
<p class="alert alert-success"> {{ session()->get('message') }}</p>
#endif
For laravel 5.6.*
While trying some of the provided answers in Laravel 5.6.*, it's clear there has been some improvements which I am going to post here to make things easy for those that could not find a solution with the rest of the answers.
STEP 1:
Go to your Controller File and Add this before the class:
use Illuminate\Support\Facades\Redirect;
STEP 2:
Add this where you want to return the redirect.
return Redirect()->back()->with(['message' => 'The Message']);
STEP 3:
Go to your blade file and edit as follows
#if (Session::has('message'))
<div class="alert alert-error>{{Session::get('message')}}</div>
#endif
Then test and thank me later.
This should work with laravel 5.6.* and possibly 5.7.*
I faced with the same problem and this worked.
Controller
return Redirect::back()->withInput()->withErrors(array('user_name' => $message));
View
<div>{{{ $errors->first('user_name') }}}</div>
In blade
#if(Session::has('success'))
<div class="alert alert-success" id="alert">
<strong>Success:</strong> {{Session::get('success')}}
</div>
#elseif(session('error'))
<div class="alert alert-danger" id="alert">
<strong>Error:</strong>{{Session::get('error')}}
</div>
#endif
In controller
for success
return redirect()->route('homee')->with('success','Successfully Log in ');
for error
return back()->with('error',"You are not able to access");
laravl 8
Route::post('/user/profile', function () {
// Update the user's profile...
return redirect('/dashboard')->with('status', 'Profile updated!');
});
Blade syntax
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
enter link description here
For Laravel 3
Just a heads up on #giannis christofakis answer; for anyone using Laravel 3 replace
return Redirect::back()->withErrors(['msg', 'The Message']);
with:
return Redirect::back()->with_errors(['msg', 'The Message']);
Laravel 5.6.*
Controller
if(true) {
$msg = [
'message' => 'Some Message!',
];
return redirect()->route('home')->with($msg);
} else {
$msg = [
'error' => 'Some error!',
];
return redirect()->route('welcome')->with($msg);
}
Blade Template
#if (Session::has('message'))
<div class="alert alert-success" role="alert">
{{Session::get('message')}}
</div>
#elseif (Session::has('error'))
<div class="alert alert-warning" role="alert">
{{Session::get('error')}}
</div>
#endif
Enyoj
I got this message when I tried to redirect as:
public function validateLogin(LoginRequest $request){
//
return redirect()->route('sesion.iniciar')
->withErrors($request)
->withInput();
When the right way is:
public function validateLogin(LoginRequest $request){
//
return redirect()->route('sesion.iniciar')
->withErrors($request->messages())
->withInput();
Laravel 5.8
Controller
return back()->with('error', 'Incorrect username or password.');
Blade
#if (Session::has('error'))
<div class="alert alert-warning" role="alert">
{{Session::get('error')}}
</div>
#endif
**Try This**
Try This Code
--- Controller ---
return redirect('list')->with('message', 'Successfully');
return redirect('list');
---- Blade view ------
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif

Resources