Laravel localization - laravel

I'm going crazy with Laravel's localization system, but I don't know what's wrong with my code.
I just wrote a language-chooser, in the Head of the document you'll see a function to get the Browser-default language, which shall get the default language.
The Language-Templates are saved as default in an array in the /resources/lang/*language*/messages.php-files.
I really need your help, because I can't see any errors.
<html>
<head>
<?php
//get Browser default language
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
App::setlocale($lang);
?>
</head>
<body>
<div class="container">
#yield('content')
<div class="well text-center">
<h1><?php echo trans('Welcome') ?></h1>
</div>
#section('content.welcome')
<div class="row text-center">
Deutsch
<label> | </label>
English
<label> | </label>
Italiano
<label> | </label>
Español
<label> | </label>
Français
<label> | </label>
日本人
<label> | </label>
Pусский
</div>
#show
</div>
#section('footer')
<nav>
© <?php echo date("Y"); ?>
<ul >
<li >
<?php echo trans('Contact') ?>
</li>
</ul>
</nav>
#show
</body>

As per my understand, you need to modify your current approach. So, here is the example you can utilize for project.
.Env
APP_LOCALE=en
config/app.php
'locale' => env('APP_LOCALE', 'en'),
HTML
<ul class="dropdown-menu" role="menu">
<li>{!! link_to('lang/en', trans('menus.language-picker.langs.en')) !!}</li>
<li>{!! link_to('lang/es', trans('menus.language-picker.langs.es')) !!}</li>
<li>{!! link_to('lang/fr-FR', trans('menus.language-picker.langs.fr-FR')) !!}</li>
<li>{!! link_to('lang/it', trans('menus.language-picker.langs.it')) !!}</li>
<li>{!! link_to('lang/pt-BR', trans('menus.language-picker.langs.pt-BR')) !!}</li>
<li>{!! link_to('lang/ru', trans('menus.language-picker.langs.ru')) !!}</li>
<li>{!! link_to('lang/sv', trans('menus.language-picker.langs.sv')) !!}</li>
</ul>
Route
get('lang/{lang}', 'LanguageController#languageRoute');
LanguageController
namespace App\Http\Controllers;
class LanguageController extends Controller
{
function languageRoute($lang)
{
session()->put('locale', $lang);
return redirect()->back();
}
}
LocaleMiddleware
namespace App\Http\Middleware;
use Closure;
class LocaleMiddleware
{
protected $languages = ['en', 'es', 'fr-FR', 'it', 'pt-BR', 'ru', 'sv'];
public function handle($request, Closure $next)
{
if(session()->has('locale') && in_array(session()->get('locale'), $this->languages))
{
app()->setLocale(session()->get('locale'));
}
return $next($request);
}
}
add middleware to kernel.php
And Finally , my lang folder looks like
en
es
fr-FR
it
pt-BR
ru
sv
and each folder contains:
alerts.php
auth.php
crud.php
labels.php
menus.php
navs.php
pagination.php
passwords.php
roles.php
strings.php
validation.php
Hope, this example help you much, but however it's just a example still you can update as per your requirement. If still something confused please let me know, I will try to update question in further detail.

Related

How do I do pagination on my code in Laravel?

So my front-end Lists of Businesses are not in paginated style. But I do not know how to do it. Can anyone please help? The code I posted is in my BusinessListController.php
BusinessListController.php
`<?php
namespace App\Http\Controllers;
use App\Models\Business;
use App\Models\Category;
use App\Models\Location;
use Illuminate\Http\Request;
class BusinessListController extends Controller
{
public function index(Request $request)
{
$businesses = Business::query()
->with('location')
->whereFilters($request->only(
['search', 'category', 'location']
))
->get();d
return view('pages.business-list', [
'businesses' => $businesses,
'locations' => Location::all(),
'categories' => Category::all()
]);
}
}`
And then here is the code for my view blade front-end
Business-List.blade.php
<div class="row business-list-row mx-auto">
#foreach ($businesses as $business)
<div class="col-md-4">
<div class="card shadow border-light mb-3">
<img
src="https://cdn1.clickthecity.com/images/articles/content/5d6eba1f4795e0.58378778.jpg"
class="card-img-top" alt="...">
<div class="card-body">
<div class="d-flex justify-content-between">
<div>
<h4 class="card-title h6" style="font-weight: bold;">
{{Str::limit($business->name, 20, $end='...')}}
</h4>
<div class="">
<p class="card-text">
{{ $business->location?->name }}
</p>
<p class="card-text" style="color: #32a852;">
{{ $business->category?->name}}
</p>
</div>
</div>
<div class="align-self-center">
<a href="{{ route('store', $business->id) }}" class="btn btn-info stretched-link">
Visit
</a>
</div>
</div>
</div>
</div>
</div>
#endforeach
</div>
So you need to do three things.
In Controller:
$businesses = Business::query()
->with('location')
->whereFilters($request->only(
['search', 'category', 'location']
))
->paginate(15);
put the number of items you need on a single page. here I put 15.
Put this under the </div> of your list.
{{ $business->links() }}
Put this inside the App\Providers\AppServiceProvider boot method.
use Illuminate\Pagination\Paginator;
public function boot()
{
Paginator::useBootstrapFive(); // or
Paginator::useBootstrapFour();
}
This depends upon which version of Bootstrap you are using.
Still confused? Checkout Laravel Pagination Documentation
Just remove ->get();d and add paginate
example
ModelName()->paginate();

Laravel Backpack file upload

I recently installed laravel backpack
And my form has a pdf file to upload
I read the tutorial on backpack but was unable to solve it
I Debugged and found that
request()->hasFile() is empty
no file in request
and html code of the add form has no enctype="" in it
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FileUploadController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('file-upload', [FileUploadController::class, 'fileUpload'])->name('file.upload');
Route::post('file-upload', [FileUploadController::class, 'fileUploadPost'])->name('file.upload.post');
Create FileUploadController
app/Http/Controllers/FileUploadController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FileUploadController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function fileUpload()
{
return view('fileUpload');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function fileUploadPost(Request $request)
{
$request->validate([
'file' => 'required|mimes:pdf,xlx,csv|max:2048',
]);
$fileName = time().'.'.$request->file->extension();
$request->file->move(public_path('uploads'), $fileName);
return back()
->with('success','You have successfully upload file.')
->with('file',$fileName);
}
}
Create Blade File
resources/views/fileUpload.blade.php
<!DOCTYPE html>
<html>
<head>
<title>laravel 8 file upload example - ItSolutionStuff.com.com</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading"><h2>laravel 8 file upload example - ItSolutionStuff.com.com</h2></div>
<div class="panel-body">
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ route('file.upload.post') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-6">
<input type="file" name="file" class="form-control">
</div>
<div class="col-md-6">
<button type="submit" class="btn btn-success">Upload</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Laravel Backpack is for admin CRUD functionalities. All you need to do in the admin controller is to define the field type as "Browse" for file upload. Example, below is to upload and file. It will upload single file in your laravel default filesystem and save the path in photo_path field of database.
$this->crud->addField([ // Photo
'name' => 'photo_path',
'label' => "Photo",
'type' => 'browse'], 'both');
This is for the admin only, if you want upload feature for frontend, Backpack API's are not for that. In that case, check in Laravel docs.

URL with two parameters

I want to generate URL with two parameters. In my web.php I created a route:
Route::get('/pojedinacni-turnir/{godina}/kolo/{kolo}', [
'uses' => 'Frontend\PojedinacniTurnirController#show',
'as' => 'pojedinacni.turnir',
]);
where are my two parameters are godina and kolo.
In my Controller I create show function with two parameters: id from godina and id from kolo.
Here is code from my controller:
<?php
namespace App\Http\Controllers\Frontend;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Sezona;
use App\TurnirPojedinacni;
class PojedinacniTurnirController extends Controller
{
public function show($id_sezona, $id_kolo)
{
$sezone = Sezona::orderBy('godina', 'desc')->get();
$sezona = Sezona::findOrFail($id_sezona);
$kola = TurnirPojedinacni::where('sezona_id', $id_sezona)->orderBy('id', 'asc')->get();
$kolo = TurnirPojedinacni::findOrFail($id_kolo);
return view('frontend.pojedinacni_turnir', compact('sezone', 'sezona', 'kola', 'kolo'))->render();
}
}
When I try to check my URL i get this message:
Missing required parameters for [Route: pojedinacni.turnir] [URI: pojedinacni-turnir/{godina}/kolo/{kolo}]. (View: C:\WebSites\TkPazin\TK_Pazin\resources\views\frontend\pojedinacni_turnir.blade.php)
I don't understand error because i try URL with two parameters. I created URL with id's that exist like this:
{{ route('pojedinacni.turnir', ['godina' => 1, 'kolo' => 1]) }}
and even then i get the same error message.
Update: added blade file
#extends('layouts.frontend')
#section('title', 'TK Pazin | Pojedinačni turnir')
#section('css')
<link href="/css/style_pojedinacni_turniri.css" rel="stylesheet"/>
#endsection
#section('content')
<!-- Page Content -->
<div class="container">
<!-- Page Heading -->
<h1 class="my-4" style="text-align:center; color: #ba3631;">Pojedinačni turniri {{ $sezona->godina }}</h1>
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
#foreach($sezone as $sezona)
<li class="breadcrumb-item">{{ $sezona->godina }}</li>
#endforeach
</ol>
</nav>
<div class="row mb-5">
<div class="col-12 col-md-2 mb-5">
<div class="list-group">
#foreach($kola as $kolo)
<button type="button" class="list-group-item list-group-item-action">{{ $kolo->naziv }}</button>
#endforeach
</div>
</div>
</div>
</div>
<!-- /.container -->
#endsection
You blade file shows that you have only added 1 parameter
#foreach($sezone as $sezona)
<li class="breadcrumb-item">{{ $sezona->godina }}</li>
#endforeach
Add the additional parameter
{{ $sezona->godina }}

Two controllers one route laravel

I can currently show the index page along with a list of posts. The user can select a post to view post details. For this I have:
Routes:
Route::get('/', 'PostsController#showPosts');
Route::get('post/{slug}', 'PostsController#showPostDetails');
Controller:
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
class PostsController extends Controller
{
public function showPosts()
{
$posts = Post::simplePaginate(2);
return view('index', ['posts' => $posts]);
}
public function showPostDetails($slug)
{
$post = Post::findBySlug($slug);
return view('post.show',['post'=>$post]);
}
}
Model:
public static function findBySlug($slug)
{
return static::where('slug', $slug)->first();
}
index
#extends('layouts.index')
#section('header')
<!-- Page Header -->
<header class="masthead" style="background-image: url('img/home-bg.jpg')">
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<div class="site-heading">
<h1>Train Testing</h1>
<span class="subheading">Testing Times</span>
</div>
</div>
</div>
</div>
</header>
#stop
#section('content')
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
#foreach ($posts as $post)
#include('partials.post', ['post' => $post])
#endforeach
{{ $posts->links() }}
</div>
</div>
#stop
partials/post.blade.php
<div class="post-preview">
<a href="/post/{{ $post->slug }}">
<h2 class="post-title">
{{ $post->title }}
</h2>
<h3 class="post-subtitle">
{{ $post->excerpt }}
</h3>
</a>
<p class="post-meta">Posted by
{{ $post->author->name }}
on {{ $post->created_at->format('l d F, Y') }}</p>
</div>
<hr>
I now want to show the posts on all other pages. My other pages currently have the route Route::get('{slug}', 'PagesController#show'); And it makes sense initially to refer back to existing code so use Route::get('{slug}', 'PostsController#showPosts'); like I did on the home page to display posts there.
However I am not sure of the best way to deal with this as I believe you can not have two controllers for one route.
For other pages I currently have:
Controller:
<?php
namespace App\Http\Controllers;
use App\Page;
use Illuminate\Http\Request;
class PagesController extends Controller
{
public function show($slug)
{
$page = Page::findBySlug($slug);
return view('page', ['page' => $page]);
}
}
page.blade:
#extends('layouts.index')
#section('header')
<!-- Page Header -->
<header class="masthead" style="background-image: url('/storage/{{ $page->image }}')">
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<div class="page-heading"> <h1>{!! $page->title !!}</h1>
<span class="subheading"></span>
</div>
</div>
</div>
</div>
</header>
#stop
#section('content')
<!-- Main Content -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
{!! $page->body !!}
</div>
</div>
</div>
#stop
Pages Controller:
use App\Page;
use App\Post;
use Illuminate\Http\Request;
class PagesController extends Controller
{
public function show($slug)
{
$posts = Post::simplePaginate(2);
$page = Page::findBySlug($slug);
return view('page', ['page' => $page, 'posts' => $posts]);
}
Then in page.blade.php I can call $posts without any errors:
#foreach ($posts as $post)
#include('partials.post', ['post' => $post])
#endforeach
{{ $posts->links() }}
Not sure if this is the neatest way but it works.

NotFoundHttpException in Handler.php line 131:

I know this is probably something really stupid but I just can't seem to fix it.
I'm getting this error
NotFoundHttpException in Handler.php line 131: No query results for model [App\Modules\Menus\Models\Menu].
And can't seem to fix it. At the moment it shouldn't even be asking for the Menu model.
Here is my route.php
Route::get('/signup', [
'uses' => 'OpenController#signup',
'as' => 'signup'
]);
Here is my OpenController.php
<?php
namespace App\Modules\Open\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Modules\Menus\Models\Menu;
use App\Modules\Authors\Models\Story;
class OpenController extends Controller
{
public function index(){
$menus_child = Menu::where('menu_id', 0)->with('menusP')->get();
$menu = Menu::where('id', 1)->orWhere('title', 'home')->firstOrFail();
return view('open::index', compact('menus_child', 'menu'));
}
public function content($id){
$menus_child = Menu::where('menu_id', 0)->with('menusP')->get();
$menu = Menu::where('id', $id)->firstOrFail();
$layout = $menu->type;
$stories = Story::where('type', 'public')->get();
return view('open::public/'.$layout, compact('menus_child', 'menu', 'stories'));
}
public function signup(){
echo "sign up";
die();
}
}
Here is my signup.blade.php
#extends('templates::layouts.public')
#section('content')
<h1>signup blade</h1>
#stop
Here is my public.blade.php layout
<!DOCTYPE html>
<html>
<head>
<title>Website</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Cherry+Swash|Crafty+Girls|Homemade+Apple|Italianno|Parisienne|Ranga|Rochester" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
{!! Html::style('css/bootstrap.min.css') !!}
{!! Html::style('css/style.css') !!}
{!! Html::script('js/jquery-3.1.1.min.js') !!}
{!! Html::script('js/bootstrap.min.js') !!}
{!! Html::script('js/main.js') !!}
</head>
<body>
<div class="container">
<div id="main">
<div id="header">
<div id="logo">
<div class="row">
<div class="col-lg-6">
<h1>Website</h1>
</div>
<div class="col-lg-6">
<div class="slogan">
{!! Html::link('/signup', 'Signup') !!} / {!! Html::link('/login', 'Login') !!}
</div>
</div>
</div>
</div>
#include('menus::menu')
</div>
<div id="site_content">
<div id="content">
#yield('content')
</div>
</div>
</div>
</div>
</body>
</html>
And this is my menu.blade.php
<div id="menubar">
<ul class="nav navbar-nav" id="menu">
#foreach($menus_child as $grandfather)
#if($grandfather->menu_id)
<li>
#elseif($grandfather->title == 'Home')
<li class="parent {{ menu_active([$grandfather->id]) }}">
#elseif(count($grandfather->menusP()->where('menu_id', '>', 0)->get()))
<li class="dropdown {{ menu_active([$grandfather->id]) }}">
#else
<li class="parent {{ menu_active([$grandfather->id]) }}">
#endif
#if(count($grandfather->menusP()->where('menu_id', '>', 0)->get()))
{!! HTML::decode(HTML::link($grandfather->id, $grandfather->title.'<span class="caret"></span>', array('class' => 'dropdown-toggle')))!!}
#else
{!! HTML::link($grandfather->id, $grandfather->title) !!}
#endif
#if(count($grandfather->menusP))
<ul class="dropdown_menu">
#foreach($grandfather->menusP as $father)
#if($father->menu_id)
<li class="parent_child">
#else
<li>
#endif
{!! HTML::link($father->id, $father->title) !!}
#endforeach
</ul>
#endif
#endforeach
</ul>
</div>
I found out what caused the issue. It was how I had my routes placed. So all I did was put my signup route on top of my routes and that solved my problem
#Gus, #Isis
This post helped me solve a very similar (or possibly same) issue. In my particular case, I immediately realized it was simple user error - and this may help explain why this may happen...
Consider visiting the following URL given the subsequent routes:
GET app.com/team/add-favorite
[bad] Routes:
// Bad Routing Logic
Route::get('/team/{team}', 'TeamController#show');
Route::get('/team/add-favorite', 'UserTeamController#default');
Route::get('/team/add-favorite/{conference}', 'UserTeamController#index');
Obviously, the 2nd route ( /team/add-favorite ) will never be called because it's simply going to route to /team/{team} with the [team] parameter filled with a value of "add-favorite".
My solution was to also simply re-arrange the order of the routes, like so...
[better] Routes:
// Still not good practice, but works
Route::get('/team/add-favorite', 'UserTeamController#default');
Route::get('/team/add-favorite/{conference}', 'UserTeamController#index');
Route::get('/team/{team}', 'TeamController#show');
This is still definitely not best practice, but will at least allow each of the routes to resolve properly.
app.com/team/add-favorite will now match the first route, while something like app.com/team/17 will still fall to the 3rd listed route and be handed to the TeamController with an appropriate ID.
Again - I don't recommend routing this way with "shared" endpoints as it could definitely still cause problems. i.e - better hope there were never a team with and ID = 'add-favorite'. Highly improbable, but you get the point...
Hope this helps!

Resources