Laravel 5.4 set locale in session - laravel-5

Update.
I would like to know how to set locale in session.
my language picker isnt' input type, but just text. here is blade fragment - this is language picker:
<div class = "col-lg-5 col-md-5" id = "lang">
<ul id = "lang_menu">
<li class = "language active">Latviešu</a></li>
<li class = "language">Pусский</a></li>
<li class = "language">English</a></li>
</ul>
</div>
Here are routes:
Route::get('/', 'PagesController#index');
Route::get('/mafia', 'PagesController#mafia');
Route::get('/games', 'PagesController#games');
Route::get('/discounts', 'PagesController#discounts');
Route::get('/tournaments', 'PagesController#tournaments');
Route::get('/gallery', 'PagesController#gallery');
Route::get('/aboutus', 'PagesController#aboutus');
also i have transladet files who works fine when i changing locale in config
<<----------UPDATED----------------->>
Now i got so far but still its not working. I made this code from one tutorial where all works. I did the same and its not working.
Here is lang choosing Blade :
<ul id = "lang_menu">
<li class = "language active">Latviešu</li>
<li class = "language">Pусский</li>
<li class = "language">English</li>
</ul>
Here is routes:
Route::get('locale/{locale?}', array('as'=>'set-locale', 'uses'=>'LanguageController#setLocale'));
Here is my LanguageController:
use Illuminate\Http\Request;
use Session;
use URL;
class LanguageController extends Controller
{
public function setLocale($locale='en'){
if (!in_array($locale, ['en', 'ru', 'lv'])){
$locale = 'en';
}
Session::put('locale', $locale);
return redirect(url(URL::previous()));
}
}
And here is middleware "Locale":
use Closure;
use Session;
use Config;
use App;
class Locale
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$locale=Session::get('locale', Config::get('app.locale'));
App::setLocale($locale);
return $next($request);
}
}
And added in Kernel.php:
\App\Http\Middleware\Locale::class,
\Illuminate\Session\Middleware\StartSession::class,

You can set a route to configure the locale (see Configuring The Locale), and redirect back to the previous url:
Route::get('locale/{locale}', function ($locale) {
$validLocale = in_array($locale, ['lv', 'ru', 'en']);
if ($validLocale) {
App::setLocale($locale);
}
return back();
});
When visitors select locale, get users to your route:
<div class = "col-lg-5 col-md-5" id = "lang">
<ul id = "lang_menu">
<li class = "language{{ App::isLocale('lv') ? ' active' : '' }}">Latviešu</li>
<li class = "language{{ App::isLocale('ru') ? ' active' : '' }}">Pусский</li>
<li class = "language{{ App::isLocale('en') ? ' active' : '' }}">English</li>
</ul>
</div>

In middleware you must use session obtained from request, not from helper session() or Session::get() !
public function handle($request, Closure $next)
{
if ($request->session()->has('locale') ) {
$locale = $request->session()->get('locale');
App::setLocale($locale);
}
return $next($request);
}

Related

Laravel Fortify Logout Redirect

Hello guys is there any ways to redirect the logout function of Fortify?
<div class="nav-link" id="nav-bar-logoutbutton">
<form method="POST" action="{{ route('logout') }}">
#csrf
<button class="btn btn-secondary btn-sm" type="submit">Logout</button>
</form>
</div>
this is my blade logout
You can do the following:
Create a new LogoutResponse class and implement your redirect logic into the toResponse method:
"app/Http/Responses/LogoutResponse.php"
<?php
namespace App\Http\Responses;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Laravel\Fortify\Contracts\LogoutResponse as LogoutResponseContract;
use Symfony\Component\HttpFoundation\Response;
class LogoutResponse implements LogoutResponseContract
{
/**
* Create an HTTP response that represents the object.
*
* #param Request $request
*
* #return Response
*/
public function toResponse($request)
{
return $request->wantsJson()
? new JsonResponse('', 204)
: redirect('www.example.com');
}
}
Now you can bind the new response into the service container in the boot method of your FortifyServiceProvider:
"app/Providers/FortifyServiceProvider.php"
public function boot()
{
$this->app->singleton(
\Laravel\Fortify\Contracts\LogoutResponse::class,
\App\Http\Responses\LogoutResponse::class
);
}
In your config/fortify.php, add:
'redirects' => [
'logout' => 'login',
],
Just create a new post request in your routes/web.php
Route::post('logout', [ClientController::class, 'logout'])->name('logout');
Now in your controller, create a function to handle the request, make sure to include the Auth class at the top.
use Auth;
/* Process the logout request */
public function logout(Request $request) {
Auth::logout();
return redirect('/login')->with(['msg_body' => 'You signed out!']);
}
Instead of /login, you can redirect to anywhere.

Laravel Redirect back to same page after changing locale

The way I implemented multilang is through middleware and routes.
Middleware Localization.php looks like this:
public function handle(Request $request, Closure $next)
{
$locale = $request->segment(1);
if(empty($locale)) {
return redirect()->to('/' . app()->getLocale());
}
if(in_array($locale, ['en','it'])) {
App::setLocale($locale);
$request->except(0);
}
return $next($request);
}
And in my web.php I have:
Route::get('locale/{locale}', function ($locale){
\Session::put('locale', $locale);
$path = Route::getCurrentRoute()->getPath();
return redirect($path);
})->name('langroute');
In blade I'm using it like this:
<a class="dropdown-item" href="{{ url('/en') }}">
How can I redirect back to same page after changing to another lang?
I hope that this answer helps someone because I know many struggle with this.
The credits goes to #khaledw62 who answered me in laracasts: Link here
Im writing the answer here to.
1- You can manage it on blade like this:
#php
$thisUrl = url()->current().'/';
if (app()->getlocale() == 'en') {
$newUrl = str_replace('/en/', '/it/', $thisUrl);
}else{
$newUrl = str_replace('/it/', '/en/', $thisUrl);
}
#endphp
And you can redirect to $newYrl like this:
<a class="dropdown-item" href="{{ $newUrl }}">
2- Another way is sharing a global variable to all of your views as following in your AppServiceProvider:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
$thisUrl = url()->current().'/';
if (app()->getlocale() == 'en') {
$newUrl = str_replace('/en/', '/it/', $thisUrl);
}else{
$newUrl = str_replace('/it/', '/en/', $thisUrl);
}
View::share('newUrl', $newUrl);
}
}
And you can redirect in blade same like before:
<a class="dropdown-item" href="{{ $newUrl }}">
Happy coding!

Argument 1 passed to App\Mail\SurveyMail::__construct() must be an instance of App\Mail\User, array give

I'm trying to send emails to the users who have been accepted by the admin using mailable api in Laravel 5.3.
class SurveyMail extends Mailable
{
use Queueable, SerializesModels;
public $user;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct(User $user)
{
$this->user=$user;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('mail.send')
->from('monsite#chezmoi.com');
}
and this is my controller
class EmailController extends Controller
{
public function send(Request $request,User $user)
{
Mail::to($user)
->send(new SurveyMail ($request->except('_token')));
}
}
the view:
<body style="background: black; color: white">
<h2>Prise de contact sur mon beau site</h2>
<p>Réception d'une prise de contact avec les éléments suivants :</p>
<ul>
<li><strong>Nom</strong> : {{ $user->name }}</li>
<li><strong>Email</strong> : {{ $user->email }}</li>
</body>
it seems that the argument User which is passed to the constructor is not accepted. Please, how can I fix this?
In the SurveyMail construct add App\ or add use App\User on the top of it :
public function __construct(App\User $user)
{
$this->user=$user;
}
And then the call should be like this :
Mail::to($user)
->send(new SurveyMail ($user));
In your SurveyMail constructor, you've type hinted $user as a User object but while instantiating the class you've passed the request data which is an array. Try this
Mail::to($user)->send(new SurveyMail($user));
Also, there is no import for User object so it assumed that your User class is inside App\Mail. which it is not. So, import your App\User model on top of your class.
use App\User; // <- Add this here
class SurveyMail extends Mailable
Also, in your view. you forgot to close the ul tag.
<body style="background: black; color: white">
<h2>Prise de contact sur mon beau site</h2>
<p>Réception d'une prise de contact avec les éléments suivants :</p>
<ul>
<li><strong>Nom</strong> : {{ $user->name }}</li>
<li><strong>Email</strong> : {{ $user->email }}</li>
</ul>
</body>
You can do following which worked for me.
From your SurveyMail constructor, remove 'User' before $user and make the constructor look like following
public function __construct($user)
{
$this->user = $user;
}
This should fix the error.

How to show the comments which belongs to the post?

I'm creating a news feed kind of thing where users can post anything and the post will have comments also. I'm able to create the newsfeed and the comment section, but my real problem is I'm not able to show the comments which belongs to the post. Right now all the comments are displayed under every news feed. Though I've declared the eloquent relationship between feed and comment but still I'm not able to save the feed_id in comment table.
This is my FeedsController:-
<?php namespace App\Http\Controllers;
use Request;
use Auth;
use Sentinel;
use App\Feed;
use App\Http\Requests;
use App\Blog;
use App\Http\Controllers\Controller;
use App\Comment;
class FeedsController extends Controller
{
public function index() {
$comments = Comment::latest()->get();
$feeds = Feed::where('user_id', Sentinel::getUser()->id)->latest()->get();
$blogs = Blog::latest()->simplePaginate(5);
$blogs->setPath('blog');
return view('action.index')->with('feeds', $feeds)->with('comments', $comments)->with('blogs', $blogs);
}
public function store(Requests\CreateFeedRequest $request){
$requet = $request->all();
$request['user_id'] = Sentinel::getuser()->id;
Feed::create($request->all());
return redirect('home');
}
public function storecomment(Requests\CommentRequest $request, Feed $feed)
{
$comment = new Comment;
$comment->user_id =Sentinel::getuser()->id;
$comment->feed_id = $request->feed_id;
$comment->comment = $request->comment;
$comment->save();
return redirect('home');
}
}
This is the models:
Comment model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $fillable = [
'comment',
'user_id',
'feed_id'
];
public function feed()
{
return $this->belongsTo('App\Feed');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
Feed model:
use Illuminate\Database\Eloquent\Model;
class Feed extends Model
{
protected $fillable = [
'feed_id',
'user_id',
'feed_content'
];
public function user()
{
return $this->belongsTo('App\User');
}
public function comment()
{
return $this->hasMany('App\Comment');
}
}
User model:-
<?php namespace App;
use Cartalyst\Sentinel\Users\EloquentUser;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends EloquentUser {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes to be fillable from the model.
*
* A dirty hack to allow fields to be fillable by calling empty fillable array
*
* #var array
*/
protected $fillable = [];
protected $guarded = ['id'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* To allow soft deletes
*/
use SoftDeletes;
protected $dates = ['deleted_at'];
public function feeds()
{
return $this->hasMany('App\Feed');
}
public function comment()
{
return $this->hasMany('App\Comment');
}
}
This is my feed.blade.php where I'm displaying the feeds output and commnets
#foreach($feeds as $feed)
<article class="media">
<div class="well">
<div class="pull-left">
<img class="profile" src="{{ URL::to('/uploads/users/'.$feed->user->pic) }}" class="img-responsive" alt="Image" style="width:48px;height:48px;padding-right : 10px;padding-bottom: 5px;">
</div>
<strong>{{ $feed->user->first_name }}
{{ $feed->user->last_name }}
<small> posted </small>
</strong>
{{ $feed->created_at->diffForHumans() }}<br><hr>
{{ $feed->feed_content }}
<hr>
{!! Form::open(['url' => 'home/{storecomment}']) !!}
<div class="form-group">
{!! Form::text('comment', null, ['class'=>'form-control', 'rows'=>3, 'placeholder'=>"Comment"]) !!}
</div>
<div class="form-group feed_post_submit">
{!! Form::submit('Comment', ['class' => 'btn btn-default btn-xs']) !!}
</div>
{!! Form::close() !!}
#foreach($comments as $comment)
<div class="pull-left">
<img class="profile" src="{{ URL::to('/uploads/users/'. $comment->user->pic) }}" class="img-responsive" alt="Image" style="width:48px;height:48px;padding-right : 10px;padding-bottom: 5px;">
</div>
{{ $comment->user->first_name }}
{{ $comment->created_at->diffForHumans() }}
{{ $comment->comment }}<hr>
#endforeach
</div>
</article>
#endforeach
Can anyone tell me how to store the feed_id into comment table and displaying the comments according to the feed. Thank You. I'm using Laravel 5.1
Based on our lengthy convo -
To save the feed_id (which is our foreign key for future relationships), you need to set/send the feed_id in your POST request. Laravel is not magic and won't know this automatically. You can do this by adding a hidden input, like so:
<input type="hidden" name="feed_id" value="{{ $feed->feed_id }}" />
In your FeedController, change your index to this:
public function index() {
// $comments = Comment::latest()->get(); remove this
// notice the "with" below. I'm eager loading in relations here
$feeds = Feed::with('comments', 'user')->where('user_id', Sentinel::getUser()->id)->latest()->get();
$blogs = Blog::latest()->simplePaginate(5);
$blogs->setPath('blog');
return view('action.index', compact('feeds', 'blogs'));
}
Feed Model should have the correct relationships, as below:
class Feed extends Model
{
protected $fillable = [
'feed_id',
'user_id',
'feed_content'
];
public function user()
{
return $this->belongsTo('App\User', 'id', 'user_id');
}
public function comments()
{
return $this->hasMany('App\Comment', 'feed_id', 'feed_id');
}
}
Comment Model should have the correct relationships, as below:
class Comment extends Model
{
protected $fillable = [
'comment',
'user_id',
'feed_id'
];
public function feed()
{
return $this->belongsTo('App\Feed');
}
public function user()
{
return $this->hasOne('App\User', 'id', 'user_id');
}
}
Now you should be able to run your foreach as you currently have it.

Laravel request service return json

When you validate your data using a request service how do you return the the errors in json format like e.g.
return response->json(array("errors' => true, 'errors' => $errors));
Request Service:
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use Auth;
class MyRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
protected $action;
public function authorize()
{
if(Auth::check()) {
return true;
}
}
public function validate() {
return parent::validate();
}
public function all()
{
}
public function messages()
{
}
public function rules()
{
}
}
Controller:
public function store(MyRequest $request) {
$mymodel = new MyModel();
$mymodel->title = 'test';
$model->save();
}
You don't have to do it manually, it will automatically sends an errors response, which could be use like:
#if ($errors->has())
<div class="alert alert-danger">
#foreach ($errors->all() as $error)
{{ $error }}<br>
#endforeach
</div>
#endif
OR
#if ($errors->has('name')) <p class="help-block">{{ $errors->first('name') }}</p> #endif
OR
Skip Request and do Validator::make() and in the end do:
return response($validatorObject->messages(), 500);

Resources