htmlspecialchars error when using multiple translation files in laravel - php

I'm currently working on translations for my laravel project. It's all working fine, but only when I'm working with just one translation file.
I'm trying to keep things organised, and for that purpose I had the idea to have one translation file for the side-wide components (login/logout links, back buttons, stuff like that) and then introduce other translation files for more specific things, such as translating components found on your profile's dashboard.
Here are, for example, my English translation files:
general.php
return [
"login" => "Login",
"register" => "Register",
"logout" => "Logout",
"back" => "Back",
"postBy" => "Posted by",
"name" => "Name",
"email" => "E-Mail Address",
"pass" => "Password",
"confirmPass" => "Confirm Password",
"rememberMe" => "Remember Me",
"forgotPass" => "Forgot Your Password?",
];
dashboard.php
<?php
return [
"title" => "Your Messages",
"header" => "Message",
"create" => "Add Message",
"edit" => "Edit",
"delete" => "Delete",
];
I'm already getting errors by doing this, without even using it in my dashboard.blade.php file. The error I get is:
ErrorException (E_ERROR) htmlspecialchars() expects parameter 1 to be
string, array given (View:
C:\xampp\htdocs\messageboard\resources\views\layouts\app.blade.php)
(View:
C:\xampp\htdocs\messageboard\resources\views\layouts\app.blade.php)
while I haven't even attempted to call it with something like {{ __('dashboard.title') }}. I'm at a loss as to what's causing this error.
As requested, here is the view causing the error. I'm getting the same error no matter what page is loaded, so I'm assuming that it'll be this very view as it's basically included and expanded upon in every other view.
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>
<!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet" type="text/css">
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
</head>
<body>
<div id="app">
<nav class="navbar navbar-expand-md navbar-light navbar-laravel">
<div class="container">
<a class="navbar-brand" href="{{ url('/') }}">
<i class="far fa-envelope"></i>
{{ config('app.name', 'Messageboard') }}
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<!-- Left Side Of Navbar -->
<ul class="navbar-nav mr-auto">
</ul>
<!-- Right Side Of Navbar -->
<ul class="navbar-nav ml-auto">
<!-- Authentication Links -->
#guest
<li class="nav-item">
<a class="nav-link" href="{{ route('login') }}">{{ __('general.login') }}</a>
</li>
#if (Route::has('register'))
<li class="nav-item">
<a class="nav-link" href="{{ route('register') }}">{{ __('general.register') }}</a>
</li>
#endif
#else
<li class="nav-item dropdown">
<a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
{{ Auth::user()->name }} <span class="caret"></span>
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="/dashboard">{{ __('Dashboard') }}</a>
<a class="dropdown-item" href="{{ route('logout') }}"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
{{ __('general.logout') }}
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
#csrf
</form>
</div>
</li>
#endguest
</ul>
</div>
</div>
</nav>
<div class="container">
<main class="py-4">
#include('inc.statusmessages')
#yield('content')
</main>
</div>
</div>
</body>
</html>
The controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Message;
use App\User;
use Auth;
class MessagesController extends Controller
{
public function __construct(){
$this->middleware('auth', [
'except' => [
'index',
'show'
]
]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$messages = Message::orderBy('created_at', 'desc')->get();
return view('messages')->with('messages', $messages);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('createmessage');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'body' => 'required|min:15|max:500'
]);
// Create Message
$message = new Message;
$message->title = $request->input('title');
$message->body = $request->input('body');
$message->status = 100;
$message->user_id = auth()->user()->id;
$message->save();
return redirect('/dashboard')->with('success', 'Message Created');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$message = Message::findOrFail($id);
$user = User::findOrFail($message->user_id);
$messageData = [
'message' => $message,
'user' => $user
];
return view('showmessage')->with($messageData);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$userId = 0;
$message = Message::findOrFail($id);
if (Auth::check())
{
// The user is logged in...
$userId = Auth::user()->id;
}
if((int)$userId !== (int)$message->user_id) {
return "Poster ID: ".$message->user_id.", User ID: ".$userId;
}
return view('editmessage')->with('message', $message);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'title' => 'required',
'body' => 'required|min:15|max:500'
]);
$message = Message::find($id);
$message->title = $request->input('title');
$message->body = $request->input('body');
$message->status = 100;
$message->user_id = auth()->user()->id;
$message->save();
return redirect('/dashboard')->with('success', 'Message Updated');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$message = Message::find($id);
$message->delete();
return redirect('/dashboard')->with('success', 'Message Removed');
}
}
Any help would be appreciated. I hope I'm clear enough, and if not please let me know.

As #Magnus Eriksson pointed out, this is because you're using {{ __('Dashboard') }} in your blade view and have a dashboard.php translation file.
The __() translation helper will normally fall back to returning the string it's given when there are no matching translation keys, but in this case it does find the translation file. Since you're not using a specific key from the file such as dashboard.title, it's returning the full translation array from the file, which is then given to htmlentities() when the blade view is rendered.

Related

Undefined variable in Laravel trying to post source ID route

Currently Working on building out a news api behind a dashboard. I have just recently started getting the error Undefined variable: sourceId (View: C:\Laravel8Auth\resources\views\dashboard.blade.php).
Ive gone everywhere that has source Id and I cant see to figure out what it could be.
Here are some of the codes necessary, im using Laravel 8.x with JetStream Im fairly new at this just wanted to mess around.
web php
`<?php
use Illuminate\Support\Facades\Route;
use App\Models\Api;
use App\Http\Controllers\ApiController;
///Route::get('/', [ApiController::class,'displayNews']);
///Route::get('/fetchNewsFromSource', [ApiController::class, 'fetchNewsFromSource'])->name('fetchNewsFromSource');
///Route::post('/sourceId', 'ApiController#displayNews');
Route::get('/', 'App\Http\Controllers\ApiController#displayNews');
Route::post('sourceId', 'App\Http\Controllers\ApiController#displayNews');
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
`
Dashboard php
<!DOCTYPE html>
<html lang="{{ config('app.locale') }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>News Application with Laravel</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet" type="text/css">
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div id="appendDivNews">
<nav class="navbar fixed-top navbar-light bg-faded" style="background-color: #e3f2fd;">
<a class="navbar-brand" href="#">News Around the World</a>
</nav>
{{ csrf_field() }}
<section id="content" class="section-dropdown">
<p class="select-header"> Select a news source: </p>
<label class="select">
<select name="news_sources" id="news_sources">
<option value="{{$sourceId}} : {{$sourceName}}">{{$sourceName}}</option>
#foreach ($newsSources as $newsSource)
<option value="{{$newsSource['id']}} : {{$newsSource['name'] }}">{{$newsSource['name']}}</option>
#endforeach
</select>
</label>
<object id="spinner" data="spinner.svg" type="image/svg+xml" hidden></object>
</section>
<div id="news">
<p> News Source : {{$sourceName}} </p>
<section class="news">
#foreach($news as $selectedNews)
<article>
<img src="{{$selectedNews['urlToImage']}}" alt=""/>
<div class="text">
<h1>{{$selectedNews['title']}}</h1>
<p style="font-size: 14px">{{$selectedNews['description']}} <a href="{{$selectedNews['url']}}"
target="_blank">
<small>read more...</small>
</a></p>
<div style="padding-top: 5px;font-size: 12px">
Author: {{$selectedNews['author'] ? : "Unknown" }}</div>
#if($selectedNews['publishedAt'] !== null)
<div style="padding-top: 5px;">Date
Published: {{ Carbon\Carbon::parse($selectedNews['publishedAt'])->format('l jS \\of F Y ') }}</div>
#else
<div style="padding-top: 5px;">Date Published: Unknown</div>
#endif
</div>
</article>
#endforeach
</section>
</div>
</div>
</body>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Scripts -->
<script src="{{ asset('js/site.js') }}"></script>
</html>
apicontroller.php supposed to grab from this to get the news api
<?php
namespace App\Http\Controllers;
use App\Models\Api;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
class ApiController extends Controller
{
/**
* #param Request $request
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function displayNews(Request $request)
{
$response = $this->determineMethodHandler($request);
$apiModel = new Api();
$response['news'] = $apiModel->fetchNewsFromSource($response['sourceId']);
$response['newsSources'] = $this->fetchAllNewsSources();
return view('dashboard', $response);
}
/**
* #param $request
* #return mixed
*/
protected function determineMethodHandler($request)
{
if ($request->isMethod('get')) {
$response['sourceName'] = config('app.default_news_source');
$response['sourceId'] = config('app.default_news_source_id');
} else {
$request->validate([
'source' => 'required|string',
]);
$split_input = explode(':', $request->source);
$response['sourceId'] = trim($split_input[0]);
$response['sourceName'] = trim($split_input[1]);
}
return $response;
}
/**
* #return mixed
*/
public function fetchAllNewsSources()
{
$response = Cache::remember('allNewsSources', 22 * 60, function () {
$api = new Api;
return $api->getAllSources();
});
return $response;
}
}
You should pass an array with variables to views
view('dashboard', ["sourceId" => 1, /* and so on */]);
I can't understand what are you doing there.

Symfony paths issues

I'm currently working on a basic Symfony project to discover this Framework, my website identifies some French rap albums and gives infos about it, then I created 2 Controllers : "DefaultController" and "AlbumsController". In the fist one, I implements some functions to displays some music lyrics and I use path names for the links and it's well work but with the second Controller I do the exact same things and it's not working. (Sorry for bad English).
Attached -> The problematic code
DefaultController :
<?php
namespace App\Controller;
use App\Entity\Musique;
use App\Form\AlbumsType;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\Controller\AlbumsController;
use App\Repository\AlbumsRepository;
use App\Repository\MusiqueRepository;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\Albums;
class DefaultController extends AbstractController
{
/**
* #Route("/", name="index")
*/
public function index()
{
return $this->render('index.html.twig', [
'title' => 'Accueil',
]);
}
/**
* #Route("/albums", name="albums")
*/
public function albums()
{
$repo = $this->getDoctrine()->getRepository(Albums::class);
$albums = $repo->findAll();
return $this->render('albums/index.html.twig', [
'albums' => $albums,
]);
}
/**
* #Route("/musiques", name="musiques")
*/
public function musiques()
{
$repo = $this->getDoctrine()->getRepository(Musique::class);
$musiques = $repo->findAll();
return $this->render('musiques.html.twig', [
'title' => 'Liste des Musiques',
'$musiques' => $musiques,
]);
}
/**
* #Route("/musiques/{id}", requirements={"id": "[1-9]\d*"}, name="randMusique")
* #throws \Exception
*/
public function randomMusique()
{
$random = random_int(1, 100);
$repo = $this->getDoctrine()->getRepository(Musique::class);
$musique = $repo->find($random);
return $this->render('randomMusique.html.twig', [
'musique' => $musique,
]);
}
}
AlbumsController :
<?php
namespace App\Controller;
use App\Entity\Albums;
use App\Form\AlbumsType;
use App\Repository\AlbumsRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* #Route("/albums")
*/
class AlbumsController extends AbstractController
{
/**
* #Route("/", name="albums_index", methods={"GET"})
*/
public function index(AlbumsRepository $albumsRepository): Response
{
return $this->render('albums/index.html.twig', [
'albums' => $albumsRepository->findAll(),
]);
}
/**
* #Route("/new", name="album_new", methods={"GET","POST"})
*/
public function new(Request $request): Response
{
$album = new Albums();
$form = $this->createForm(AlbumsType::class, $album);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($album);
$entityManager->flush();
return $this->redirectToRoute('albums_index');
}
return $this->render('albums/new.html.twig', [
'album' => $album,
'formAlbum' => $form->createView(),
]);
}
/**
* #Route("/{id}", name="albums_show", methods={"GET"})
*/
public function show(Albums $album): Response
{
return $this->render('albums/show.html.twig', [
'album' => $album,
]);
}
/**
* #Route("/{id}/edit", name="albums_edit", methods={"GET","POST"})
*/
public function edit(Request $request, Albums $album): Response
{
$form = $this->createForm(AlbumsType::class, $album);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('albums_index');
}
return $this->render('albums/edit.html.twig', [
'album' => $album,
'form' => $form->createView(),
]);
}
/**
* #Route("/{id}", name="albums_delete", methods={"DELETE"})
*/
public function delete(Request $request, Albums $album): Response
{
if ($this->isCsrfTokenValid('delete'.$album->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($album);
$entityManager->flush();
}
return $this->redirectToRoute('albums_index');
}
}
base.html.twig :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}Projet — PHP{% endblock %}</title>
<link rel="stylesheet" href="https://bootswatch.com/4/darkly/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="{{ asset('css/style.css')}}">
{% block stylesheets %}{% endblock %}
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light">
<a class="navbar-brand" href="/">France-Rap</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor03"
aria-controls="navbarColor03" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarColor03">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="{{ path('index') }}">Accueil</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ path('albums') }}">Liste des Albums</a>
</li>
{#
<li class="nav-item">
<a class="nav-link" href="{{ path('musiques') }}">Liste des Musiques</a> // The path isn't working
</li>
<li class="nav-item">
<a class="nav-link" href="{{ path('randMusique') }}">Musique Aléatoire</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ path('album_new') }}">Créer un Album</a>
</li>
#}
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
</ul>
{% block search %}{% endblock %}
</div>
</nav>
{% block body %}{% endblock %}
{% block javascripts %}{% endblock %}
</body>
</html>
This is the error :
Render error
Resultat of the command :
php bin/console debug:router musiques
In the secreen shot of the error i can see that your view is picked up from cache try runing follwing comand:
php bin/console cache:clear

Laravel 5.8 Trying to get property 'unreadNotifications' of non-object

Working on my friend's code, it seems all features like Post, Tag, Category, etc are working fine. I want to add a feature to upload a pdf and download it from front end. After adding DownloadController and Downloads model, It shows varies errors. Most irritating error is
Trying to get property 'unreadNotifications' of non-object(View: /var/www/html/tes/resources/views/admin/layouts/header.blade.php)
Routes:
//Admin Routes
Route::group(['namespace'=>'Admin'], function (){
Route::get('admin/home','HomeController#index')->name('admin.index');
//Users Routes
Route::resource('admin/user','UserController');
//Roles Routes
Route::resource('admin/role','RoleController');
//permissions Routes
Route::resource('admin/permission','PermissionController');
//Download Manager Routes - CV
Route::resource('admin/cv','Downloadcontroller');
//Post Routes
Route::DELETE('postDeleteSelected','PostController#deleteSelected')->name('deleteSelected');
Route::get('admin/post/remove/{post}','PostController#remove')->name('posts.remove');
Route::get('admin/post/trash','PostController#trashed')->name('posts.trashed');
Route::get('admin/post/recover/{id}','PostController#recover')->name('posts.recover');
Route::get('markAsRead','PostController#markRead')->name('markRead');
Route::resource('admin/post','PostController');
//Tag Routes
Route::resource('admin/tag','TagController');
//Category Routes
Route::resource('admin/category','CategoryController');
//Admin Auth Routes
Route::get('admin-login','Auth\LoginController#showLoginForm')->name('admin.login');
Route::post('admin-login','Auth\LoginController#login');
});
Controller:
namespace App\Http\Controllers\Admin;
use App\Model\admin\admin;
use App\Model\user\Downloads;
use App\Http\Controllers\Controller;
use App\Notifications\TaskCompleted;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Notification;
class Downloadcontroller extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function index()
{
return view('admin.cv.show');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$data = new Downloads;
if ($request->file('file')){
$file = $request->file('file');
$filename = time().'.'.$file->getClientOriginalExtension();
$request->file->move('storage/'.$filename);
$data->file = $filename;
}
$data->title = $request->title;
$data->description = $request->description;
$data->uploader = Auth::user()->name;
$data->save();
$users = admin::where('id','3')->get();
Notification::send($users, new TaskCompleted($data));
return redirect(route('cv.index'))->with('toast_success','Post Created Successfully');
}
View: in admin.cv.show, the template extends the admin.layouts.app. and the problematic view is here.
<li class="nav-item dropdown">
<a class="nav-link" data-toggle="dropdown" href="#">
<i class="far fa-bell"></i>
#if (Auth::check())
#if(auth()->user()->unreadNotifications->count())
<span class="badge badge-warning navbar-badge">{{auth()->user()->unreadNotifications->count()}}</span>
#endif
#endif
</a>
<div class="dropdown-menu dropdown-menu-lg dropdown-menu-right">
<span class="dropdown-item dropdown-header">
Mark All as Read
</span>
#foreach(auth()->user()->unreadNotifications as $notification)
<div class="dropdown-divider"></div>
<a href="#" class="dropdown-item" style="background-color: lightgrey">
<p><i class="fas fa-envelope mr-2"></i>{{$notification->data['data']}}
<span class="float-right text-muted text-sm">{{$notification->created_at->diffForHumans()}}</span>
</p>
</a>
#endforeach
#foreach(auth()->user()->readNotifications->take(5) as $notification)
<div class="dropdown-divider"></div>
<a href="#" class="dropdown-item">
<p><i class="fas fa-envelope mr-2"></i>{{$notification->data['data']}}
<span class="float-right text-muted text-sm">3 mins</span>
</p>
</a>
#endforeach
<div class="dropdown-divider"></div>
See All Notifications
</div>
</li>

Route Laravel Error

this is my routes
Route::get('/', 'frontcontroller#index');
Route::get('/index.html', 'frontcontroller#index');
Route::get('/checkout.html', 'frontcontroller#checkout');
Route::get('/furniture.html', 'frontcontroller#furniture');
Route::get('/login.html', 'frontcontroller#login');
Route::get('/products.html', 'frontcontroller#products');
Route::get('/register.html', 'frontcontroller#register');
Route::get('/single.html', 'frontcontroller#single');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::group(['prefix' => 'admin','middleware'=>'auth'], function () {
Route::get('/', function () {
return view('admin.index');
})->name('admin.index');
});
this is a side navigation:
{{-- Side Navigation --}}
<div class="col-md-2">
<div class="sidebar content-box" style="display: block;">
<ul class="nav">
<!-- Main menu -->
<li class="current"><a href="{{route('admin.index')}}"><i class="glyphicon glyphicon-home"></i>
Dashboard</a></li>
<li class="submenu">
<a href="#">
<i class="glyphicon glyphicon-list"></i> Products
<span class="caret pull-right"></span>
</a>
<!-- Sub menu -->
<ul>
<li>Add Product</li>
</ul>
</li>
</ul>
</div>
</div> <!-- ADMIN SIDE NAV-->
This is the route function
/**
* Get the URL to a named route.
*
* #param string $name
* #param mixed $parameters
* #param bool $absolute
* #return string
*
* #throws \InvalidArgumentException
*/
public function route($name, $parameters = [], $absolute = true)
{
if (! is_null($route = $this->routes->getByName($name))) {
return $this->toRoute($route, $parameters, $absolute);
}
throw new InvalidArgumentException("Route [{$name}] not defined.");
}
Why I have this problem?
Route [product.index] not defined.
(View:C:\Users\Antonio\Desktop\uni\musicshop\resources\views\admin\layout\includes\sidenav.blade.php)
(View:C:\Users\Antonio\Desktop\uni\musicshop\resources\views\admin\layout\includes\sidenav.blade.php)
(View:C:\Users\Antonio\Desktop\uni\musicshop\resources\views\admin\layout\includes\sidenav.blade.php)
This is the code of the problem:
enter image description here
you should set name route
Route::get('/products.html', 'frontcontroller#products')->name('product.index');

How to display the view generated by the controller in Laravel?

I have a difficulty displaying the view I created. I am studying laravel now and I found this useful article how to create a simple CRUD.
http://scotch.io/tutorials/simple-laravel-crud-with-resource-controllers
But I am stuck at displaying the first layout using the routes. Here's my code so far.
routes.php
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::get('/', function()
{
return View::make('hello');
});
Route::resource('nerd','NerdController');
Nerd.php (model)
<?php
class Nerd extends Eloquent
{
}
?>
NerdController.php (controller)
<?php
class NerdController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
//get all nerds
$nerds = Nerd::all();
//load the view
return View::make('nerds.index')-
>with('nerds', $nerds);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
return View::make('nerds.create');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
}
database setting
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'laravel_forums',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
index.blade.php (view)
<!DOCTYPE html>
<html>
<head>
<title>Look! I'm CRUDding</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<nav class="navbar navbar-inverse">
<div class="navbar-header">
<a class="navbar-brand" href="{{ URL::to('nerds') }}">Nerd Alert</a>
</div>
<ul class="nav navbar-nav">
<li>View All Nerds</li>
<li>Create a Nerd
</ul>
</nav>
<h1>All the Nerds</h1>
<!-- will be used to show any messages -->
#if (Session::has('message'))
<div class="alert alert-info">{{ Session::get('message') }}</div>
#endif
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
<td>Email</td>
<td>Nerd Level</td>
<td>Actions</td>
</tr>
</thead>
<tbody>
#foreach($nerds as $key => $value)
<tr>
<td>{{ $value->id }}</td>
<td>{{ $value->name }}</td>
<td>{{ $value->email }}</td>
<td>{{ $value->nerd_level }}</td>
<!-- we will also add show, edit, and delete buttons -->
<td>
<!-- delete the nerd (uses the destroy method DESTROY /nerds/{id} -->
<!-- we will add this later since its a little more complicated than the other two buttons -->
<!-- show the nerd (uses the show method found at GET /nerds/{id} -->
<a class="btn btn-small btn-success" href="{{ URL::to('nerds/' . $value->id) }}">Show this Nerd</a>
<!-- edit this nerd (uses the edit method found at GET /nerds/{id}/edit -->
<a class="btn btn-small btn-info" href="{{ URL::to('nerds/' . $value->id . '/edit') }}">Edit this Nerd</a>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</body>
</html>
When I try to view the index using this path
http://mylocalhost/testsite/nerds
I got
Not Found
The requested URL /testsite/nerds was not found on this server.
That's all guys. I hope you can help me.
Assuming that app root URL is http://website.loc/testsite/ the solution is:
a: eighter access this URL thru web browser
http://mylocalhost/testsite/nerd
b:
// or change this
Route::resource('nerd', ...);
// to this
Route::resource('nerds', ...)
Simply you told Laravel to catch /nerd in URL but access /nerds instead. I am sure you got it now :)

Categories