Laravel 5.x: How to replace locale in URL in view/blade? - laravel

I've a blade in my views, which looks like this:
#if (App::getLocale() == 'de')
<a href="/en/dashboard">
<i class="fa fa-language">ENGLISH</i>
</a>
#elseif (App::getLocale() == 'en')
<a href="/de/dashboard">
<i class="fa fa-language">GERMAN</i>
</a>
#endif
This creates a button, which allows me to switch to the other language.
Well... The URL could also be one of these:
/en/settings
/en/logbook
I want, that the button redirects to the same page, but on a different language:
/en/dashboard -> /de/dashboard
/en/settings -> /de/settings
/en/logbook -> /de/logbook
Using {{ Request::url() }} I'm able to get the current URL, but what's now the best way / solution to use this URL just with a different locale?
{{ Request::url() }} for example contains /en/dashboard and I would now need /de/dashboard.
Does there any Laravel function exist or do I need to code this with PHP within... The blade?

I have wrote this small helper function about 2 years ago. It works great when you pass $locale variable and it adds it to URL's first segment.
public static function getLocaleChangerURL($locale){
$uri = $_SERVER['REQUEST_URI'];
$uri = explode('/', $uri);
unset($uri[0]);
unset($uri[1]);
$url = url($locale);
foreach($uri as $u){
$url .= '/'.$u;
}
return $url;
}

I would prefer this way.
public static function getLocaleChangerURL($locale)
{
$uri = request()->segments();
$uri[0] = $locale;
return implode($uri, '/');
}

Related

Missing required parameters for route bus.edit

I got an error when I access menu, that show
Missing required parameters for [Route: bus.edit] [URI: bus/{bu}/edit]
.
Code for view from button
<a href="{{ route('bus.edit', ['bus' => $row["bus_id"]]) }}" class="btn btn-sm btn-warning">
Routes
Route::resource('bus', 'BusController')->middleware('auth');
For controller
public function index()
{
$data['title'] = "Buses";
$data['menu'] = 1;
$buses = DB::table('buses')
->join('brands', 'buses.brand_id', '=', 'brands.brand_id')
->get()->toArray();
$data['buses'] = json_decode(json_encode($buses), true);
$data['no'] = 1;
return view('bus.index', $data);
}
public function edit($id)
{
$data['title'] = "Edit Bus";
$data['menu'] = 1;
$data['bus'] = Bus::find($id);
$data['brands'] = Brand::all();
return view('bus.edit', $data);
}
As the error says, you need to pass a single parameter called {bu},
So change it to :
{{ route('bus.edit', ['bu' => $row["bus_id"]]) }}
Or,
{{ route('bus.edit', $row["bus_id"]) }}
Since the system for plural/singular is broken for this word, bus, in 8.x you can specifically tell the resource what the route parameter should be named:
Route::resource('bus', 'BusController')
->parameters(['bus' => 'bus'])
->middleware('auth');
This would make the route parameter bus instead of bu. Then the call to the route helper you currently have would work.

Undefined variable: foods

hi guys am in need of assistance , i know this seems to be an easy one but am a bit confused , i have a foreach loop in my main.blade.php file, which shows foods from my database it works fine but when its clicked it meant to lead to the individual post and thats where i get the error
Undefined variable: foods
heres my foreach loop in main.blade.php file
#foreach($foods as $food)
<li class="item">
<a href="{{ route('Foods.show', $food->id) }}">
<img src="{{ Storage::disk('local')->url('food_images/'.$food->image ) }}" class="img-responsive w-25 p-3" alt="Food" >
<div class="menu-desc text-center">
<span>
<h3> {{ $food->title }}</h3>
{{ $food->body }}
</span>
</div>
</a>
<h2 class="white"> #{{ $food->price }}</h2>
</li>
#endforeach
heres my main.blade.php controller
public function LoadHome()
{
$foods = Food::all();
$foods = Food::orderBy('created_at','desc')->inRandomOrder()
->limit(12)
->get();
return view('pages.home')->withFood($foods);
}
and heres Foods.show controller function
public function show($id)
{
$foods = Food::Find($id);
return view('foods.show')->withFood($foods);
}
please what am i doing wrong
Have you tried passing data from your controller to the view using this something like this:
public function show($id)
{
$foods = Food::Find($id);
return view('foods.show')->with('foods', $foods);
}
or, if you're passing multiple variables to the view:
public function show($id)
{
$foods = Food::Find($id);
$something = "else";
return view('foods.show', compact('foods', 'something'));
}
Your view doesn't know what $foods is at that point, so it's always good practice to check that foods is set before the loop:
#if (isset($foods) && $foods->count() > 0)
#foreach($foods as $food)
...
#endforeach
#endif
See the official Laravel docs for more information.
If you want the variable to be named foods in the view then you would need to use withFoods not withFood:
return view(...)->withFoods($foods);
As mentioned in the other answers, there are other ways to pass data to the views as well.
There is no data being passed to a view.
This is how you pass data to a view:
public function LoadHome()
{
$foods = Food::orderBy('created_at','desc')->inRandomOrder()
->limit(12)
->get();
return view('pages.home', ['foods' => $foods])
}
If you always want to have $foods in main.blade.php you should place this in a service provider
View::share('foods', Food::orderBy('created_at','desc')->inRandomOrder()
->limit(12)
->get());
https://laravel.com/docs/7.x/views#sharing-data-with-all-views

Parsing data in view layouts laravel 6

I want to make a profile photo on the admin page, this photo is in the layouts.template file, how can I get the $profil to be sent to the layouts.template page?
#if($profil->upload!=null)
<img src="{{asset('backend/assets/img/{{$profil->upload}}.jpg')}}" alt="..." class="avatar-img rounded-circle">
#else
<img src="{{asset('backend/assets/img/mlane.jpg')}}" alt="..." class="avatar-img rounded-circle">
#endif
and i created $profil in UserController
$auth = Auth::user()->id;
$profil = Profil_user::where('user_id',$auth)->first();
how do I get my $profil to be used in layouts.template
You can share variable along all views inside below file
app/Providers/AppServiceProvider.php
public function boot()
{
//Define your user auth call here
if(confition){
$profile_pic = 'admin.png';
} else {
$profile_pic = 'default.png';
}
\View::composer('*', function($view){
$view->with('profile_pic', $profile_pic);
});
}

How to fetch current locale in view in Laravel 5.3

I am making a bilingual app. I am using same routes for each but I am using different views for both languages. Whenever I want to redirect to a route I want to pass {{ route('test.route', 'en') }}. Where I am passing en, I want to fetch the current locale value from the view and then pass it to the route. Please help.
try this. It will give the locale set in your application
Config::get('app.locale')
Edit:
To use this in blade, use like the following, to echo your current locale in blade.
{{ Config::get('app.locale') }}
If you want to do a if condition in blade around it, it will become,
#if ( Config::get('app.locale') == 'en')
{{ 'Current Language is English' }}
#elseif ( Config::get('app.locale') == 'ru' )
{{ 'Current Language is Russian' }}
#endif
To get current locale,
app()->getLocale()
At first create a locale route and controller :
Route::get('/locale/{lang}', 'LocaleController#setLocale')->name('locale');
class LocaleController extends Controller
{
public function setLocale($locale)
{
if (array_key_exists($locale, Config::get('languages')))
{
Session::put('app_locale', $locale);
}
return redirect()->back();
}
}
Now you can check easily in every page:
$locale = app()->getLocale();
$version = $locale == 'en' ? $locale . 'English' : 'Bangla';

Laravel 4 MethodNotAllowedhttpException

I am get a MethodNotAllowedHttpException when I submit the form detailed below. The route appears correct to me and is syntactically the same as other post routes that are working just fine. The controller method exists but even so I think the exception is occuring before the request gets to the controller as item 4 on the left of the laravel error page says handleRoutingException right after item 3 which says findRoute. I am pretty sure I am not using restful routing the way you should in laravel 4 but that is because the tutorial I am following a laravel 3 tutorial and updating hte syntax to 4 as I go but like I said the other routes work fine so I can't figure out why this one isn't.
Template
#extends('layouts.default')
#section('content')
<div id="ask">
<h1>Ask a Question</h1>
#if(Auth::check())
#include('_partials.errors')
{{ Form::open(array('ask', 'POST')) }}
{{ Form::token() }}
<p>
{{ Form::label('question', 'Question') }}
{{ Form::text('question', Input::old('question')) }}
{{ Form::submit('Ask a Question') }}
</p>
{{ Form::close() }}
#else
<p>
<p>Please login to ask or answer questions.</p>
</p>
#endif
</div><!-- end ask -->
#stop
Route
Route::post('ask', array('before'=>'csrf', 'uses'=>'QuestionsController#post_create'));
Controller
<?php
class QuestionsController extends BaseController {
public $restful = true;
protected $layout = 'layouts.default';
public function __construct()
{
$this->beforeFilter('auth', array('post_create'));
}
public function get_index() {
return View::make('questions.index')
->with('title', 'Make It Snappy Q&A - Home');
}
public function post_create()
{
$validation = Question::validate(Input::all());
if($validation->passes()) {
Question::create(array(
'question'=>Input::get('question'),
'user_id'=>Auth::user()->id
));
return Redirect::Route('home')
->with('message', 'Your question has been posted.');
} else {
return Redirect::Route('register')->withErrors($validation)->withInput();
}
}
}
?>
I believe defining public $restful = true; is how it was done in Laravel 3. In Laravel 4 you define a restful controller in your routes like so:
Route::controller('ask', 'QuestionsController');
Then to define the functions you would not use an underscore to separate them. You must use camel case like so:
public function getIndex()
{
// go buck wild...
}
public function postCreate()
{
// do what you do...
}
For RESTful Controllers you should define the route using Route::controller method, i.e.
Route::controller('ask', 'QuestionsController');
and controller methods should be prefixed with http verb that it responbds to, for example, you may use postCreate and you have post_create instead, so it doesn't look like a Restful controller.
You are using public $restful = true; in your controller, this is not being used in Laravel-4, and public $restful = true; may causing the problem, so remove this line.

Resources