How to change prefix locale in blade laravel? - laravel

I have middleware
public static function getLocale()
{
$mainLanguage = config('translatable.locale');
$languages = config('translatable.locales');
$uri = Request::path();
$segmentsURI = explode('/',$uri);
if (!empty($segmentsURI[0]) && in_array($segmentsURI[0], $languages)) {
return $segmentsURI[0];
} else {
return $mainLanguage;
}
}
public function handle($request, Closure $next)
{
$locale = self::getLocale();
if($locale) {
App::setLocale($locale);
}
return $next($request);
}
This is my routes/web.php
Route::group(['middleware' => ['localize'],
'prefix' => App\Http\Middleware\LocaleMiddleware::getLocale()], function () {
...routes...
});
This is my header.blade, where I want to change the language of my dropdown choice
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
#foreach(config('translatable.locales') as $locale)
<a class="dropdown-item" href="#">{{strtoupper($locale)}}</a>
#endforeach
</div>
My header is connected to layout and is available on all pages.
I want my routes to look like this (example):
.../en/news
.../en/news/1
What should I write in a href so that I can change the language?
I tried {{$locale . "/" . Request::segment(2)}}
but i get .../es/news/ru/news

I resolved my issue. I added function in route
Route::get('setlocale/{lang}', function ($lang) {
$referer = Redirect::back()->getTargetUrl();
$parse_url = parse_url($referer, PHP_URL_PATH);
$segments = explode('/', $parse_url);
if (in_array($segments[1], App\Http\Middleware\LocaleMiddleware::$languages)) {
unset($segments[1]);
}
if ($lang != App\Http\Middleware\LocaleMiddleware::$mainLanguage){
array_splice($segments, 1, 0, $lang);
}
$url = Request::root().implode("/", $segments);
if(parse_url($referer, PHP_URL_QUERY)){
$url = $url.'?'. parse_url($referer, PHP_URL_QUERY);
}
return redirect($url);
})->name('setlocale');

Related

Laravel - POSTMAN Login Internal Server Error

I am using Laravel-5.8 as backend for an application. I have written all the Api for the endpoints.
Laravel: ApiController
protected function guard()
{
return Auth::guard();
}
public function returnResponse($success, $data, $errorCode = 0, $message = false) {
$response = array();
$response['success'] = $success;
$response['message'] = isset($message) ? $message : '';
if ($errorCode) {
$response['errorCode'] = isset($errorCode) ? $errorCode : 0;
}
$response['data'] = $data;
return response()->json($response, 200);
}
public function login() {
$authenticated = false;
$remember = request('remember') ? true : false;
if (Auth::guard('web')->attempt(['email' => request('email'), 'password' => request('password')], $remember)) {
$authenticated = true;
}
if ($authenticated == true) {
$user = Auth::guard('web')->user();
$date = date('Y-m-d');
$success['userId'] = $user->id;
$success['avatar'] = url('/storage/user') . '/' . $user->avatar;
// $success['points'] = $user->userPoints->sum('points');
$success['email'] = $user->email;
$success['token'] = $user->createToken('MyApp')->accessToken;
return $this->returnResponse(true, $success);
} else {
$success = array();
return $this->returnResponse(false, $success, 1, 'Invalid User Credential');
}
}
api.php
Route::group([
], function () {
Route::post('login', 'ApiController#login');
Route::post('register', 'ApiController#register');
Route::post('forgetPassword', 'ApiController#forgetPassword');
Route::group([
'middleware' => 'auth:api'
], function() {
Route::get('logout', 'AuthController#logout');
Route::get('user', 'AuthController#user');
});
});
When I test the login Post Request on the POSTMAN, I got the error shown below:
What could have caused the error?
i think you have declare index() multiple times in your controller so please check and if there is multiple times declaration of index() then just remove anyone.

Laravel 5.4 Add a difference between views

I use the same view to show one post and random post
routes
Route::get('posts/{id}', 'PostsController#show')->name('posts.show');
Route::get('get-random-post', 'PostsController#getRandomPost');
methods in PostsController
public function show($id) {
$post = Post::findOrFail($id);
return view('posts.show', compact('post'));
}
public function getRandomPost() {
$post = Post::inRandomOrder()
->where('is_published', 1)->first();
return redirect()->route('posts.show', ["id" => $post->id]);
}
but now I need to add a small difference between two views. How can I do that?
UPD
I added variable $randomPost to methods in Controller
public function show($id) {
$randomPost = false;
$post = Post::findOrFail($id);
return view('posts.show', compact('post', 'randomPost'));
}
public function getRandomPost() {
$randomPost = true;
$post = Post::inRandomOrder()
->where('is_published', 1)->first();
return redirect()->route('posts.show', ["id" => $post->id]);
}
and added code below to show view
#if($randomPost)
some text
#endif
but I don't know how to pass variable from getRandomPost() to view?
UPD2
As result I used session, it works but I'm not sure about it
method
public function getRandomPost() {
$post = Post::inRandomOrder()
->where('is_published', 1)->first();
session()->flash('random_post', 'ok');
return redirect()->route('posts.show', ["id" => $post->id]);
}
view
#extends('layouts.app')
#section('content')
Home page
<h2>#{{$post->id}}</h2>
{!! nl2br(e($post->text)) !!}
<?php if(session()->has('random_post')){
echo '<div style="text-align: center">';
echo link_to_action('PostsController#getRandomPost', 'Random Post', $parameters = array(), $attributes = array());
echo '</div>';
}?>
#stop
You can use session flash, it lasts only on subsequent request:
// set
session()->flash('random_post', 'ok');
// check
if(session()->has('random_post')){
// is random
I guess the easiest way would be to call the function from the getRandomPost by passing a default variable through.
public function show($id, $randomPost = false) {
$post = Post::findOrFail($id);
return view('posts.show', compact('post', 'randomPost'));
}
public function getRandomPost() {
$post = Post::inRandomOrder()->where('is_published', 1)->first();
$this->show($post->id, true);
}

Laravel Passing Variable from a controller to another Controller

I'm trying to pass a variable from a controller to another controller I tried using
Redirect::to('dashboard/'.$ssid.'/')->with(compact('wname'))
but does not work any idea how can I achieve this?
here is my code
Route
Route::get('dashboard/{ssid}/', 'HomeController#showDash');
LoginController
public function post_index()
{
if(Auth::attempt($credentials)){
$users = User::where('username','=',$email)->get();
foreach ($users as $value):
$activated = $value['a_status'];
$wname = $value['wholename'];
endforeach;
if($activated == 1):
$red= Redirect::to('dashboard/'.$ssid.'/')->with(compact('wholename'));
else:
$red= View::make('login');
endif;
return $red;
}
}
HomeController
public function showDash($ssid,$wholename)
{
foreach ($wholename as $userVal):
$fn = $userVal['firstname'];
$ln = $userVal['lastname'];
endforeach;
return View::make('dashboard')->with(compact('fn'));
}
The error I'm having is that Missing argument 2 for HomeController::showDash() as per laravel's debugger..
Updated answer based on the comments:
public function post_index()
{
if(Auth::attempt($credentials)){
$users = User::where('username','=',$email)->get();
foreach ($users as $value){
$activated = $value['a_status'];
$wname = $value['wholename'];
}
if($activated == 1) {
Redirect::to('dashboard/'.$ssid.'/')->with(['wholename' => $wholename]);
}
return View::make('login');
}
public function showDash($ssid)
{
$wholename = (Session::has('wholename')) ? Session::get('wholename') : [];
foreach ($wholename as $userVal) {
$fn = $userVal['firstname'];
$ln = $userVal['lastname'];
}
return View::make('dashboard')->with(compact('fn'));
}
Everything else can stay as is.
Update: fixed erroneous space in 'whole name' (autocorrect did that, sorry).

Codeigniter database check

i am currently working on a project where users can save note snippets in there own little user area.
I was wondering how would i check if the id of an item exists for example if a user visits
http://mysite.com/view/1 and there is a note snippet of 1 it will display all the data relating to the id of one. Now if the user was to change the url to lets say 1000, that id doesnt exist and the view just errors.
i want to be able to redirect them back to a certain page with a error message "snippet does not exist" etc.
heres what i have so far ( i currently already have a conditional statement in here to check if the snippet is private, then if it is redirect back to /publicsnippets)
Controller:
class Publicsnippets extends CI_Controller {
function __construct()
{
parent::__construct();
if (!$this->tank_auth->is_logged_in()) {
redirect('/login/');
}
$this->load->model('dashboard_model');
$this->data['user_id'] = $this->tank_auth->get_user_id();
$this->data['username']= $this->tank_auth->get_username();
}
public function index()
{
$this->data['public_snippets'] = $this->dashboard_model->public_snippets();
$this->load->view('dashboard/public_snippets', $this->data);
}
public function view($snippet_id)
{
$snippet = $this->dashboard_model->get_snippet($snippet_id);
if ($snippet['state'] === 'private')
{
$this->session->set_flashdata('message', "<b style=\"color:red;\">You are not allowed to view this snippet!</b>");
redirect('/publicsnippets');
} else {
$this->data['snippet'] = $snippet;
}
$this->load->view('dashboard/view_public_snippet', $this->data);
}
}
Model:
class Dashboard_model extends CI_Model {
public function public_snippets()
{
$this->db->select('id, title, description, tags, author, date_submitted');
$query = $this->db->get_where('snippets', array('state' => 'public'));
return $query->result_array();
}
public function private_snippets()
{
$this->db->select('id, title, description, tags, author, date_submitted');
$query = $this->db->get_where('snippets', array('user_id' => $this->tank_auth->get_user_id()));
return $query->result_array();
}
public function add_snippet($data)
{
$this->db->insert('snippets', $data);
$id = $this->db->insert_id();
return (isset($id)) ? $id : FALSE;
}
public function get_snippet($snippet_id) {
$query = $this->db->get_where('snippets', array('id' => $snippet_id));
return $query->row_array();
}
public function update_snippet($snippet_id, $data)
{
$this->db->where('id', $snippet_id);
$this->db->update('snippets', $data);
}
public function delete_snippet($snippet_id)
{
$this->db->where('id', $snippet_id);
$this->db->delete('snippets');
}
}
View:
<h3>Description</h3>
<p><?php echo $snippet['description']; ?></p>
<h3>Tags</h3>
<p><?php echo $snippet['tags']; ?></p>
<h3>Date Submitted</h3>
<p><?php echo $snippet['date_submitted']; ?></p>
<h3>Snippet</h3></pre>
<pre class="prettyprint"><?php echo $snippet['code_snippet']; ?></pre>
You work is fine just add a check like this in your view method
Controller
public function view($snippet_id)
{
$snippet = $this->dashboard_model->get_snippet($snippet_id);
if($snippet){
if ($snippet['state'] === 'private')
{
$this->session->set_flashdata('message', "<b style=\"color:red;\">You are not allowed to view this snippet!</b>");
redirect('/publicsnippets');
} else {
$this->data['snippet'] = $snippet;
}
$this->load->view('dashboard/view_public_snippet', $this->data);
}else{
$this->session->set_flashdata('message', "<b style=\"color:red;\">snippet does not exist</b>");
redirect('/publicsnippets');
}
}
if no row is found in get_snippet method the $snippet will contain false or null
and the second block of condition will run.
In your model change get_snippet() to check for rows:
public function get_snippet($snippet_id) {
$query = $this->db->get_where('snippets', array('id' => $snippet_id));
if ($query->num_rows() > 0) {
return $query->row_array();
} else {
return false;
}
}
Then in your controller:
if ($snippet = $this->dashboard_model->get_snippet($snippet_id)) {
// code if snippet exists
} else {
// code if snippet doesn't exist
}
OR
$snippet = $this->dashboard_model->get_snippet($snippet_id);
if ($snippet) {
// etc...

Codeigniter - Facebook Login and registeration sing PHP SDK

I am using Facebook PHP SDK with Codeigniter to do login and registration using Facebook. For this I am using This tutorial
my controller 'facebooktest.php' code is:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Facebooktest extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('input');
$this->load->library('session');
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->library('security');
}
function Facebooktest() {
parent::Controller();
$cookies = $this->load->model('facebook_model');
}
function index() {
$this->load->view('facebooktest/test2');
}
function test1() {
$data = array();
$data['user'] = $this->facebook_model->get_facebook_cookie();
$this->load->view('facebooktest/test1', $data);
}
function test2() {
$data['friends'] = $this->facebook_model->get_facebook_cookie();
$this->load->view('facebooktest/test2', $data);
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
?>
view 'test2.php' has code as:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Kent is Learning CodeIgniter - Test 2</title>
</head>
<body>
<fb:login-button autologoutlink="true"
onlogin="window.location.reload(true);"></fb:login-button>
<div style="width:600px;">
<?
if(isset($friends)){
foreach($friends as $friend){
?>
<img src="http://graph.facebook.com/<?=$friend['id'];?>/picture" title="<?=$friend['name'];?>" />
<?
}
}
?>
</div>
<p><?=anchor('facebook_connect/page4','Go back to page 4 of the tutorial');?></p>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({appId: '457228377680583', status: true, cookie: true, xfbml: true});
FB.Event.subscribe('auth.sessionChange', function(response) {
if (response.session) {
// A user has logged in, and a new cookie has been saved
window.location.reload(true);
} else {
// The user has logged out, and the cookie has been cleared
}
});
</script>
</body>
</html>
And model 'facebook_model.php' has code:
<?php
class Facebook_model extends CI_Model {
function __construct() {
parent::__construct();
}
function get_facebook_cookie() {
$app_id = '457228377680583';
$application_secret = '01f660b73bc085f0b78cd22322556495';
if (isset($_COOKIE['fbs_' . $app_id])) {
echo "dfgdsf";exit;
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
} else {
return null;
}
}
function getUser() {
$cookie = $this->get_facebook_cookie();
$user = #json_decode(file_get_contents(
'https://graph.facebook.com/me?access_token=' .
$cookie['access_token']), true);
return $user;
}
function getFriendIds($include_self = TRUE) {
$cookie = $this->get_facebook_cookie();
$friends = #json_decode(file_get_contents(
'https://graph.facebook.com/me/friends?access_token=' .
$cookie['access_token']), true);
$friend_ids = array();
foreach ($friends['data'] as $friend) {
$friend_ids[] = $friend['id'];
}
if ($include_self == TRUE) {
$friend_ids[] = $cookie['uid'];
}
return $friend_ids;
}
function getFriends($include_self = TRUE) {
$cookie = $this->get_facebook_cookie();
print_r($cookie);
$friends = #json_decode(file_get_contents(
'https://graph.facebook.com/me/friends?access_token=' .
$cookie['access_token']), true);
if ($include_self == TRUE) {
$friends['data'][] = array(
'name' => 'You',
'id' => $cookie['uid']
);
}
return $friends['data'];
}
function getFriendArray($include_self = TRUE) {
$cookie = $this->get_facebook_cookie();
$friendlist = #json_decode(file_get_contents(
'https://graph.facebook.com/me/friends?access_token=' .
$cookie['access_token']), true);
$friends = array();
foreach ($friendlist['data'] as $friend) {
$friends[$friend['id']] = array(
'name' => $friend['name'],
'picture' => 'http://graph.facebook.com/'.$friend['id'].'/picture'
);
}
if ($include_self == TRUE) {
$friends[$cookie['uid']] = 'You';
}
return $friends;
}
}
?>
The problem is that, in model, it is coming inside 'getFriends()'. From there it is going inside 'get_facebook_cookie()'. But it is not going inside if(isset($_COOKIE['fbs_' . $app_id])))
and hence, it is nor displaying data that I want.
So, if possible, please let me know whats wrong with my code.
Thanks in advance....

Resources