Laravel 5.6 - A shared name for route resources - php

While creating an admin menu, i was wondering how to set active class item. The menu item have to stay active if the controller is showing, editing or doing something else.
sidebar.blade.php
<li class="nav-item">
<a class="nav-link {{ (Route::current()->getName() == 'posts' ? 'active' : '') }}" href="/admin/posts">Posts</a>
</li>
routes/web.php
// POSTS
Route::resource('/admin/posts', 'Admin\PostController');
How to set a shared name for all resources (index, create, show, etc.)?
I was hoping to do something like this but...
Route::resource('/admin/posts', 'Admin\PostController')->name('posts');
Thanks

Naming Resource Routes
By default, all resource controller actions have a route name; however, you can override these names by passing a names array with your options:
Route::resource('photos', 'PhotoController')->names([
'create' => 'photos.build'
]);
You can find more options in the documentation.

work in laravel 9 try in other version
Route::resource('vente', VenteController::class,
['names'=>['index'=>'vente.index']]);
call it in menu
vente

Related

Missing required parameters for [Route: homepage.edit] with link in layout

I'm new to Laravel 5.4 and php and I'm having some trouble to do my routing, so I wish you would explain to me what's going on !
I'm developing a back office for my future projects, and for my current project I need to be able to update data sent to the homepage. The edit of the page and the update of the data is now fully functional, I'm just having some trouble to do the link in the layout. Pretty sure it's a trivial problem, yet i'm having trouble figuring it out.
Here is my code :
web.php :
Route::group(['prefix' => 'admin', 'middleware' => 'admin'], function()
{
Route::resource('homepage', 'Admin\HomeController');
});
HomeController :`
public function edit($id) {
$contentExists = Homepage::first();
$homepage = Homepage::findOrFail($id);
return view('admin/homepage/edit', compact('homepage', 'contentExists'));
}`
In the layout :
<ul class="list-unstyled">
<li>
Page d'accueil
</li>
</ul>
Now for that I know I need to pass a parameter to the route, so I did like so :
<ul class="list-unstyled">
<li>
Page d'accueil
</li>
</ul>
But then it says the homepage variable is not defined, and I have no idea where I can define this variable since I'm in the layout, and also have no idea what needs to be inside this variable, what's his purpose... Can you help me with that ?
route second parameter, must be an array like this for example:
route('homepage.edit', ['id' => 2])

Laravel 5.1 - Pass parameter to Breadcrumbs

I use davejamesmiller Breadcrumbs package. I am wondering how to pass a parameter to a breadcrumb, something like an id.
In the docs (here) it says that is possible, but can't find the way to do it.
My goal es to do a breadcrumb like this: Dashboard \ User \ New Model. Where New Model its a form to add model data with some relationship with the user. Without the user_id param the link for User won't work.
Any idea?
You can pass global variable
\View::share ( 'variable2', $variable2 );
if render breadcrumbs in layout
or You need render breadcrumbs in `user.new_model.blade
#section('content')
{!! Breadcrumbs::render('page', $page) !!}
#stop`
my way
Create template
breadcrumbs.blade.php
with content
#if(!empty($breadcrumbs))
<ol class="breadcrumb">
<li>{!! link_to_route('main', 'Home') !!}</li>
#foreach($breadcrumbs as $bread)
#if(isset($bread['url']))
<li>{!! link_to($bread['url'], $bread['name']) !!}</li>
#else
<li>{!! $bread['name'] !!}</li>
#endif
#endforeach
</ol>
#endif
and connect it to layout
#include('breadcrumbs')
and in your action pass array of links
\View::share('breadcrumbs', [
['url' => route('collection.show', ['id'=>$data->collection, 'url'=>$data->collection]), 'name' => $data->collection->name],
['name' => $data->article]
]);
There is another way. As general, in each view just calling Breadcrumbs::render() should create the hierarchy of the breadcrumbs links depending on the routes defined in routes/breadcrumbs.php.
There are two essential points that you have keep in mind to go further with this solution:
The callback function that found in breadcrumbs.php routs definition is the place from which you should pass your parameters.
Giving correct name to your web route from routes/web.php which will be used later in routes/breadcrumbs.php
Checkout the following code snippets that demonstrates the above two points:
//Point1: routes/breadcrumbs.php
Breadcrumbs::register('job.edit', function($breadcrumbs, $job, $title)
{
$breadcrumbs->parent('job','job');
$breadcrumbs->push($title, route('job.edit', $job));
});
Breadcrumbs::register('job.edit.install', function($breadcrumbs, $job, $title)
{
$breadcrumbs->parent('job.edit',$job, $title);
$breadcrumbs->push('Job Install Equipments', route('job.edit.install','job'));
});
In the above code we passed $job and $title through the callback function.
//Point2 routes/web.php
Route::get('/job/edit/{job}', 'JobController#edit')->name('job.edit');
Route::get('/job/install-equipments/{job}', 'JobController#installEquipments')->name('job.edit.install');
We give a name to the route through the name method , Laravel 5.4, which allow us to define the routes correctly in Point1.
The last step, is what you have do in the view file. Here I will show you the last one regarding /job/install-equipments which should be rendered in the breadcrumb as the last element and its parent is job/edit with parameter job which handles the primary key id
//install.equipments.blade.php
#extends('layouts.main')
#section('content')
{!! Breadcrumbs::render('job.edit.install',$job->id, __('Edit').': '.$job->title) !!}
The above will render a breacrumbs look like:
Home / Job / Edit: title of
job / Job Install Equipment
The required parameters that handles breadcrumbs render are supplied un the above render method i.e through $job->id and __('Edit').': '.$job->title) , the last just adjusting the text and it could be done inside the callback function of breadcrumbs routes.

CakePHP view not rendering

I have a basic application being baked by CakePHP.
Now i want to add a new action'listjobs' in my model controller class and a corresponding 'listjobs' view in the /Template/Job/listjobs.ctp.
From my model's index view i added one more action in the side navigation bar.
like this
<li><?= $this->Html->link(__('View Jobs'),['action' => 'listjobs']) ?></li>
When i click on the link 'View Jobs' control is directed to the action method of my model's controller but its not taking the list jobs 's view.
Code for my action method
public function listjobs()
{
$this->log("inside list jobs",'debug');
$this->render('listjobs');
}
The listjobs.ctp contains a very basic code as following
<div class="actions columns large-2 medium-3">
<h3><?= __('Actions') ?></h3>
<ul class="side-nav">
<li>< Git Hub >
</li>
<li>< Stack overflow >
</li>
</ul>
</div>
Not able to find out why the view is not rendered rather the index view is getting rendered.
Links loaded according to chrome console in order
(1) http://localhost/myjobs/job/listjobs
(2) http://localhost/myjobs/job
So (1) should have been loaded with the view..it should not been redirected to (2)
Regards,
Saurav
I think you need to use like this.
<li><?php echo $this->Html->link('View Jobs',array('controller' => 'MyModel', 'action' => 'listjobs')); ?></li>
Your view will be.
public function listjobs()
{
$this->log("inside list jobs",'debug');
}
I think you don't need to render, your view will be render by default, you will need to send data like that $this->set(compact('VarName'));
Secondly $this->log("inside list jobs",'debug'); if log is a method then you need to set action, then it will be.
$this->setAction('log');
Try, if you get error, then let me know. If your work proper then, you view will work.
http://localhost/myjobs/job/listjobs
this link defines.
http://localhost/SiteName/ControllerName/ActionName/Parameter
Get review and study this page.
http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html
Thanks
ok...i did some debugging of the cakephp framework code.
I was using an auth component for my login functionality.
I found that the newly added action was not allowed to pass the through filter of auth component. so i added the newly added action in the beforefilter method of appcontroller like this. i guess the crud operations are already added in the filter by default.
$this->Auth->allow(['index', 'view', 'display','listjobs','add','delete']);
cheers,
Saurav

Add "active" class in blade depending on current translated Laravel route

Using the package mcamara/laravel-localization in Laravel 5.1 I managed to localize my site and also to translate the routes. The problem is now the following: How can I add a custom class "active" via blade template depending on the current route?
I have tried so far using HTML::macro but it seems the package laravelcollective/html: "5.1.*" isn't fully compatible (especially macros) with L5.1.
Even if I would manage to use an macro I can not use the Request::is('about') because the routes are translated. I'm pretty sure here has to be an easy approach...
Example routes:
www.sitename.com/en/about = www.sitename.com/ro/despre => route to same controller/action
Try this!
<li class="#if (Request::is('/')) {{'active'}} #endif">Home <span class="sr-only">(current)</span></li>
<li class="#if (Request::is('about')) {{'active'}} #endif">About</li>
<li class="#if (Request::is('contact')) {{'active'}} #endif">Contact</li>
With inspiring help from #keithm and from here I did the following:
First extend blade with a new directive, built directly in the AppServiceProvider.php
Blade::directive('activeState', function($expression) {
return '<?php echo activeClass('. $expression . '); ?>';
});
Then in your helpers file (if you don't have one you can create it into app/Http/helpers.php) add the following
function activeClass($url) {
return Request::url() == $url ? 'active' : '';
}
In blade directly use then the following directive:
<a href="{{ URL::route('front.portfolio.index') }}" class="nav-block #activeState(URL::route('front.portfolio.index'))">
Not sure if I got your question but is this what you're looking for?
<span class="someClass #if (Request::url('/myurl') active #endif"></span>
Sorry missed that part of the question :).
I didn't test it this way but it should work:
#if (Request::url($variable or $pattern .'/restofuri')
A little late to the party, but i also had the same issue and solved it with the laravel helper function url()->current() and the localization package helper function localizeURL
<a href="{{LaravelLocalization::localizeURL(trans('routes.my-route'))}}"
class="{{(url()->current() == LaravelLocalization::localizeURL(trans('routes.my-route'))) ? "active" : "" }}">
{{trans('navigation.my-route')}}</a>

Phalcon PHP - Get Controller Name in View

I have a Site Layout with a top nav bar, I need to set the class to active depending on the controller which changes when the user clicks on different pages.
views->index.phtml
<li class='<?php echo (isset($this->controllerName) && $this->controllerName == 'about') ? 'active' : '' ?>'>About Us</li>
<li class='<?php echo (isset($this->controllerName) && $this->controllerName == 'services') ? 'active' : '' ?>'>Member Sevices</li>
I was hoping that Phalcon had a view function or maybe something I can put in the bootstrap so it worked for all pages with out me having to remember to set the controllerName variable in each Controller manually.
Inside your view access your router service :
$this->router->getControllerName()
$this->router->getActionName()
or if you are using volt you can use the short hand
router.getControllerName()
router.getActionName()
That will work for your use case, but if you find that your menu logic becomes too unwieldy, there are several methods to achieve what you are attempting to do.
The easiest I find is to use javascript, but that doesn't have a fallback if they have js disabled(1%). If you want to cover 100% of your audience you could use a method like the Phalcon team did in INVO using an element library: https://github.com/phalcon/invo/blob/master/app/library/Elements.php

Categories