How to configure html builder for secure protocol (https) in laravel4.2 - laravel-4

How to configure url or base url in Laravel4.2 for secures protocol https without set manual in html builder.
{{ HTML::style('front_assets/plugins/bootstrap/css/bootstrap.min.css') }}
{{ HTML::style('front_assets/css/style.css')}}
<!-- CSS Implementing Plugins -->
{{ HTML::style('front_assets/plugins/font-awesome/css/font-awesome.min.css') }}
{{ HTML::style('front_assets/plugins/sky-forms/version-2.0.1/css/custom-sky-forms.css') }}
{{ HTML::style('front_assets/plugins/scrollbar/src/perfect-scrollbar.css') }}
{{ HTML::style('front_assets/plugins/fullcalendar/fullcalendar.css') }}
{{ HTML::style('front_assets/plugins/fullcalendar/fullcalendar.print.css',array('media' => 'print')) }}

It's not clear what you need. If you page URL is in https scheme, every asset URL on that page will be generated in https automatically, but if you need only certain types of assets to be linked by https on page requested by http, you have to implement your own custom HtmlBuilder that overrides helper methods you need to be forced to generate https URLs
<?php namespace MyApp\Html;
use Illuminate\Html\HtmlBuilder;
class MyAppHtmlBuilder extends HtmlBuilder {
public function style($url, $attributes = array(), $secure = true)
{ ^^^^
return parent::style($url, $attributes, $secure)
}
}
Then in app.php config you should replace default HtmlServiceProvider with your custom MyAppHtmlServiceProvider.
<?php namespace MyApp\Html;
use Illuminate\Html\HtmlServiceProvider;
use MyApp\Html\MyAppHtmlBuilder;
class MyAppHtmlServiceProvider extends HtmlServiceProvider {
protected function registerHtmlBuilder()
{
$this->app->bindShared('html', function($app)
{
return new MyAppHtmlBuilder($app['url']);
});
}
}

Related

larvel blade templates and elequent models -- how to get first element in many relationship

I have the following eloquent models (removed code to make it simple for this problem). I am trying to get the first image
class Design extends Model
{
use SoftDeletes;
protected $guarded = ['id','tags','keywords'];
public function images()
{
return $this->hasMany(DesignImage::class);
}
...
}
class DesignImage extends Model
{
use SoftDeletes;
public function design()
{
return $this->belongsTo(Design::class);
}
}
Then I have the following code that gets passed to a blade template
$data['designs'] = Design::where('quantity','>',0)->get();
return view('mailings.form',$data);
Template (Works fine; I get the name of all images
#foreach($design->images as $image)
{{ $image->name }}
#endforeach
But if I try
{{ $design->images->first()->name }}
I get Trying to get property 'name' of non-object`
If I try
{{ $design->images[0]->name }}
I get Undefined offset: 0
However if I do
#json ($design->images->first())
I get (valid)
{"id":1,"name":"Image 1 Design 1","thumb":"images/main_thumb.jpg","image":"images/main_large.jpg","design_id":1,"created_at":"2018-12-11 20:10:03","updated_at":"2018-12-11 20:10:03","deleted_at":null}
How do I get the first image in a blade template? Why am I getting this odd output?
Error occurs because latest one $design does not have image. Try this code
#foreach($designs as $design)
// your code
#php
$firstImage = $design->images()->first();
#endphp
{{ !empty($firstImage->name) ? $firstImage->name : ''}}
// other part ofcode
#endforeach
Also you can optimize this code using in controller
$data['designs'] = Design::where('quantity','>',0)->with('images')->get();
return view('mailings.form',$data);
In view
#foreach($designs as $design)
// your code
#php
$firstImage = $design->images->first();
#endphp
{{ !empty($firstImage->name) ? $firstImage->name : ''}}
// other part ofcode
#endforeach

How to retrieve items from the cache in view in Laravel?

I've stored some data in Laravel 5.5 cache in Service Provider as you can see in following:
class DataServiceProvider extends ServiceProvider
{
public function boot()
{
$user = Cache::rememberForever('user', function () {
return array('name' => 'jack', 'age' => 25);
});
}
public function register()
{
//
}
}
I retrieve items from the cache in controller by this:
$user= Cache::get('user');
But I need to retrieve cache items within views (blade), How can I access them directly in views (blade) (without passing cache as variable)?
I just want to store data in cache once, and access to it everywhere in my app with no more steps, is it possible?
Use the cache helper:
{{ cache('user')['name'] }}
Cache Facade: {{ Cache::get('user')['name'] }}
cache helper: {{ cache()->get('user')['name'] }} or {{ cache('user')['name'] }}
I would do it like this
#php
$user = Cache::get(“user”);
#endphp
{{ $user[“name”]; }}

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.

Laravel 4 specific view not loading

I am new to laravel and following a tutorial for a basic app. So far the app has a default view layouts/default.blade.php, a partial _partials/errors.blade.php and three other views questions/index.blade.php, users/new.blade.php and users/login.blade.php
The routes are defined like so
// home get route
Route::get('/', array('as'=>'home', 'uses'=>'QuestionsController#get_index'));
//user register get route
Route::get('register', array('as'=>'register', 'uses'=>'usersController#get_new'));
// user login get route
Route::get('login', array('as'=>'login', 'uses'=>'usersController#get_login'));
//user register post route
Route::post('register', array('before'=>'csrf', 'uses'=>'usersController#post_create'));
// user login post route
Route::post('login', array('before'=>'csrf', 'uses'=>'usersController#post_login'));
questions/index.blade.php and users/new.blade.php load fine and within default.blade.php
when I call /login a blank page is loaded not even with default.blade.php. I am guessing that there is a problem in my blade syntax in login.blade.php given the fact that the default.blade.php works on the other routes and as far as I can see everything else is the same but if that was teh case wouldnt the default.blade.php route at least load?
the controller method this route is calling is as follows
<?php
Class UsersController extends BaseController {
public $restful = 'true';
protected $layout = 'layouts.default';
public function get_login()
{
return View::make('users.login')
->with('title', 'Make It Snappy Q&A - Login');
}
public function post_login()
{
$user = array(
'username'=>Input::get('username'),
'password'=>Input::get('password')
);
if (Auth::attempt($user)) {
return Redirect::Route('home')->with('message', 'You are logged in!');
} else {
return Redirect::Route('login')
->with('message', 'Your username/password combination was incorrect')
->withInput();
}
}
}
?>
finally login.blade.php
#section('content')
<h1>Login</h1>
#include('_partials.errors')
{{ Form::open(array('route' => 'register', 'method' => 'POST')) }}
{{ Form::token() }}
<p>
{{ Form::label('username', 'Username') }}
{{ Form::text('username', Input::old('username')) }}
</p>
<p>
{{ Form::label('password', 'Password') }}
{{ Form::text('password') }}
</p>
<p>
{{ Form::submit('Login') }}
</p>
{{ Form::close()}}
#stop
You could also define the layout template directly from the Controller , this approach provides more flexibility , as the same View can be used with multiple layout templates .
<?php namespace App\Controllers ;
use View , BaseController ;
class RegisterController extends BaseController {
protected $layout = 'layouts.master';
public function getIndex()
{
// Do your stuff here
// --------- -------
// Now call the view
$this->layout->content = View::make('registration-form');
}
}
My example uses Namespaced Controller but the same concepts are applicable on non-Namespaced Controllers .
Notice : Our RegisterController extends Laravel's default BaseController , which makes a bit of preparation for us , see code below :
<?php
class BaseController extends Controller {
/**
* Setup the layout used by the controller.
*
* #return void
*/
protected function setupLayout()
{
if ( ! is_null($this->layout))
{
$this->layout = View::make($this->layout);
}
}
}
If a custom "Basecontroller" is defined , make sure that it also implements the "preparation" code .
I don't know what concepts are new to you , so let me make a couple arbitrary assumptions . If "namespace" and "Basecontroller" are << strange words >> , let me try to demystify these words .
Namespace : PHP's documentation is pretty well documented on this subject . My oversimplified explanation is as follows : Two skilled developers (JohnD and Irish1) decide to build their own PHP Logging Library and release the code as open source to the community .Most likely they will name their library "Log"
Now another developer would like to implement both libraries into his/her project (because JohnD's code uses MongoDB as storage medium while Irish1's code uses Redis ) . How would PHP's interpreter distinguishes the two code-bases from each other ? Simply prepend each library with a vendor name (JhonD/Log and Irish1/Log ) .
Basecontroller : Most likely your Controllers will share common functionality (a database connection , common before/after filters , a common template for a View ...... ) . It is a good practice not to define this "common functionality" into each Controller separately, but define a "Parent" Controller , from which all other Controllers will inherit its functionality . So later on , if you decide to make changes on the code , only one place should be edited .
My previous example uses " class RegisterController extends BaseController " , that BaseController is just checking if our (or any other) Child-controller has defined a property with the name of " $layout " , and if so , the View that it will instantiate will be encapsulated into that specified layout . See Laravel's flexibility , a group of Controllers share common functionality (by extending Basecontroller) but also are free to choose their own layout (if they desire to do so ) .
I have found my error
I did not have #extends('layouts.default') at the beginning of the login.blade.php template

Resources