How to change language dinamically in laravel? - php

I added a button to change language.
This is my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
class LanguageController extends Controller
{
public function __invoke(String $locale): RedirectResponse
{
app('session')->put('language', $locale);
app()->setLocale($locale);
return redirect()->back();
}
}
My routes:
<?php
use App\Http\Controllers\LanguageController;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('auth.login');
});
Route::get('/language/{locale}', LanguageController::class)->name('locale');
require __DIR__.'/auth.php';
And I put this in my blade:
#if (app()->getLocale() == 'es')
<x-responsive-nav-link :href="route('locale', ['locale' => 'en'])">
{{ __('English') }}
</x-responsive-nav-link>
#else
<x-responsive-nav-link :href="route('locale', ['locale' => 'es'])">
{{ __('Spanish') }}
</x-responsive-nav-link>
#endif
I tested it changing the locale directly in the config/app.php file and it works.
Also tried to set the locale in the AppServiceProvider but session variable "language" is not set (even though it is on the controller).
How could I do this?

My version.Right now this is the best way for me.
Route:
Route::get('locale/{locale}', function ($locale) {Session::put('locale', $locale);return redirect()->back();})->name('locale');
HeaderController function index:
public function index(): Factory|View|Application
{
$data['languages'] = Language::where('status', '=', 1)->get();
//Get or Set current language
$get_default_lang = 'uk';
$default_lang = $get_default_lang ?? 'en';
if (session()->get('locale') == null) Session::put('locale', $default_lang);
//Get Current Language
$get_current_lang = Session::get('locale');
$session_language = Language::where('code', $get_current_lang)->first();
$data['current_language_name'] = $session_language['name'];
$data['current_language_image'] = url($session_language['image']);
return view('common/header', ['data' => $data]);
}
Header Blade:
<div class="dropdown">
<button type="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<img src="{{ $data['current_language_image'] }}" alt="{{ $data['current_language_name'] }}" style="max-width:20px;margin-right:5px;" />
{{ $data['current_language_name'] }}
</button>
<div class="dropdown-menu">
<div class="p-2">
#foreach($data['languages'] as $language)
<a href="{{ route('locale', ['locale' => $language->code]) }}" class="dropdown-item d-flex align-items-center justify-content-between">
<img src="{{ url($language->image) }}" alt="{{ $language->name }}" style="max-width:20px;" />
<span>{{ $language->name }}</span>
</a>
#endforeach
</div>
</div>
</div>
Language migration:
Schema::create('language', function (Blueprint $table) {
$table->bigIncrements('language_id');
$table->string('name', 32);
$table->string('code', 5);
$table->string('image')->nullable();
$table->tinyInteger('status');
$table->timestamps();
});

Related

routes/web route me to another route

My web doesn't seem to be directing to the correct page.
Here is my blade
<div class="container">
<div class="col-lg-12 d-flex justify-content-between align-items-center">
<h2>Informations</h2>
<a href="{{ route('add-new-information') }}" class="btn text-success">
<i class="fas fa-plus-circle fa-2x"></i>
</a>
</div>
<hr>
<div class="row d-flex justify-content-center align-items-center mt-5" style="max-height: 500px !important; overflow-y: scroll">
#foreach ($informations as $info)
<div class="card col-sm-11 p-0 mb-4 clickable-item" onclick='window.location = "{{ route('admin-informations', ['id' => $info->id]) }}"'>
...
</div>
#endforeach
</div>
</div>
Here is my routes/web
Auth::routes();
Route::group(['middleware' => ['auth'], 'prefix' => '/',], function () {
Route::get('/', function () {
return redirect('/home');
});
Route::group(['prefix' => 'admin'], function() {
Route::get('/informations', [App\Http\Controllers\InformationController::class, 'index'])->name('informations');
Route::get('/informations/{id}', [App\Http\Controllers\InformationController::class, 'indexAdminInfo'])->name('admin-informations');
Route::get('/informations/add-new-information', [App\Http\Controllers\InformationController::class, 'add'])->name('add-new-information');
});
});
and here is my controller
public function indexAdminInfo($id){
$information = Information::find($id);
// $comments = Comment::where('information_id', $id)->orderByDesc('created_at')->get();
$ack_count = Acknowledge::where('information_id', $id)->count();
$user_ack = Acknowledge::where([
['information_id', '=', $id],
['user_id', '=', Auth::user()->id],
])->first();
$ack = 'FALSE';
if($user_ack != null){
$ack = 'TRUE';
}
return view('adminviews/infoadmin', compact('information', 'ack_count', 'ack', 'user_ack'));
}
public function add(){
return view('adminviews/addinfo');
}
For some reason, when I click the a tag with the href {{ route('add-new-information') }} to go to the add page 'adminviews/addinfo',
instead the page will go to the 'adminviews/infoadmin' page, which will cause an error, because no parameters are being sent.
I tried checking the code, but it looks correct to me. Can anybody find an error on this?
the problem is with your routes:
these two routes are ambiguous:
Route::get('/informations/{id}');
Route::get('/informations/add-new-information');
just think of below scenario:
router wants to route, this url : /information/add-new-information
router will hit the first defined route, because it is compatible with the definition ('/informations/{id}')
Note :{id} is a variable and can be any string
so it will go with this.
Solution
write the more restricted route first,
and more general route later:
Route::get('/informations/add-new-information');
Route::get('/informations/{id}');

How can I post an Images on my Laravel App?

Basic Informations
I'm developing a simple web app using Laravel.
and I want to add an image upload and stirage function.
My issue
I want to save the binary data of the image to the DataBase.
But there is an error message.
file_get_contents(): Filename cannot be empty
How can I solve this issue?
My Codes
2020_06_12_085454_create_attachments_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAttachmentsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('attachments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('path');
$table->text('image');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('attachments');
}
}
index2.blade.php
#extends('layouts.front2')
#section('title','mainpage')
#section('content')
<link rel="stylesheet" href="{{ asset('css/main2.css') }}">
<div class="profile">
<div class="name">
#guest
<a class="nav-link2" href="{{ route('register')}}">{{ __('Create Accout!')}}</a>
#else
<a id="navbarDropdown" class="nav-link2" href="#" role="button">
{{ Auth::user()->name }}<span class="caret"></span></a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
#csrf
</form>
#endguest
</div>
<div class="aboutme">
<tbody>
#foreach($posts as $profile)
<tr>
<td>{{ \Str::limit($profile->title, 100) }}</td>
<td>{{ \Str::limit($profile->body, 250) }}</td>
</tr>
delete
update
#endforeach
</tbody>
<br>
</div>
</div>
<div class="new">
<div class="newtitle">
<h1>New</h1>
</div>
<div class="container1">
#foreach ($images as $image)
<img src="data:image/png;base64,{{ $image->image }}" class="images" style="height: 250px; width: 250px; border-radius: 50%;">
 delete
#endforeach
<div class="more">
more...
</div>
</div>
</div>
{{ csrf_field() }}
#endsection
StoriesController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Story;
use App\Profile;
use Auth;
use App\Posts;
use App\History;
use App\Attachment;
use Carbon\Carbon;
use Storage;
class StoriesController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index(Request $request)
{
$images = Attachment::all();
$cond_title = $request->cond_title;
if ($cond_title != '') {
$posts = Profile::where('title', $cond_title)->get();
} else {
$posts = Profile::all();
}
return view('stories.index2', compact('images','posts','cond_title'));
}
public function add()
{
return view('stories.create2');
}
public function store(Request $request)
{
$image = new Attachment();
$image->image = base64_encode(file_get_contents($request->image));
$image->save();
}
You need to get the path where the temporary image is stored. To do that do
$request->file('image')
so your code becomes
public function store(Request $request)
{
$image = new Attachment();
$image->image = base64_encode(file_get_contents($request->file('image')));
$image->save();
}

Missing required parameters for [Route: voluntier.submit.get] [URI: voluntier/submit/{id}]

I am currently working on my final project, but I got this error and I have tried to change the route action on my html to {{ route('voluntier.submit.get') }} but it still shows the error. Could anyone help me to find the solution.
Thank you so much
VoluntierController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Event;
use App\City;
use App\User;
use App\VoluntierProfile;
use App\Submission;
class VoluntierController extends Controller
{
public function index()
{
$data = Event::select('events.job_desk', 'events.location', 'events.city', 'events.job_description', 'events.fee', 'cities.name as city', 'job_desks.job_desk')
->leftJoin('job_desks', 'events.job_desk', 'job_desks.id')
->leftJoin('cities', 'events.city', 'cities.id')
->get();
$data_category_liaison = Event::select('events.job_desk')
->where('id' , '=', 2)
->count();
// dd($data_category);
return view('voluntier.index', compact('data', 'data_category_liaison'));
}
public function profile()
{
return view('voluntier.profile');
}
public function createProfile()
{
$city = City::all()->where('id', '!=', '0');
return view('voluntier.profile-edit', compact('city'));
}
public function storeProfile(Request $request)
{
$profile = new VoluntierProfile();
$profile->voluntier_id = $request->input('voluntier_id');
$profile->about = $request->input('tentang');
$profile->city_id = $request->input('kota');
$profile->address = $request->input('alamat');
$profile->latest_education = $request->input('pendidikan_terakhir');
$profile->save();
}
public function submitCreate($id)
{
$event = Event::find($id)->first();
$voluntier = Voluntier::find(Auth::user()->id)->get();
// dd($voluntier);
return view('voluntier.submit', compact('data'));
}
public function submitStore($id, Request $request)
{
$event = Event::find($id);
$voluntier = Auth::user();
$submission = new Submission();
$submission->event_id = $event->id;
$submission->voluntier_id = $voluntier->id;
$submission->status_id = $request->input('status');
$submission->save();
return redirect('voluntier/dashboard');
}
}
index.blade.php
#foreach($data as $row)
<td><a href="{{ route('voluntier.submit.get', $row->id) }}" class="job-item d-block d-md-flex align-items-center border-bottom fulltime">
<div class="company-logo blank-logo text-center text-md-left pl-3">
<img src="images/company_logo_blank.png" alt="Image" class="img-fluid mx-auto">
</div>
<div class="job-details h-100">
<div class="p-3 align-self-center">
<h3>{{ $row->job_desk }}</h3>
<div class="d-block d-lg-flex">
<div class="mr-3"><span class="icon-suitcase mr-1"></span>{{ $row->location }}</div>
<div class="mr-3"><span class="icon-room mr-1"></span>{{ $row->city }}</div>
<div><span class="icon-money mr-1"></span>Rp. {{ $row->fee }}</div>
</div>
</div>
</div>
<!-- <div class="job-category align-self-center">
<div class="p-3">
<span class="text-info p-2 rounded border border-info">Full Time</span>
</div>
</div> -->
</a></td>
#endforeach
submit.blade.php
<form action="{{ route('voluntier.submit.post', $event->id) }}" method="post" class="p-5 bg-white">
My route
web.php
Route::prefix('voluntier')->group(function() {
Route::get('/login', 'Auth\LoginController#showVoluntierLoginForm')->name('voluntier.login.get');
Route::post('/login/post', 'Auth\LoginController#voluntierLogin')->name('voluntier.login.post');
Route::get('/register', 'Auth\RegisterController#showVoluntierRegisterForm')->name('voluntier.register.get');
Route::post('/register/post', 'Auth\RegisterController#createVoluntier')->name('voluntier.register.post');
Route::get('/dashboard', 'VoluntierController#index')->middleware('auth:voluntier')->name('voluntier.dashboard');
Route::get('/profile', 'VoluntierController#profile')->middleware('auth:voluntier')->name('voluntier.get');
Route::get('/profile/get', 'VoluntierController#createProfile')->middleware('auth:voluntier')->name('voluntier.profile.get');
Route::post('/profile/post', 'VoluntierController#storeProfile')->name('voluntier.profile.post');
Route::get('/submit/{id}', 'VoluntierController#submitCreate')->middleware('auth:voluntier')->name('voluntier.submit.get');
Route::post('submit/post/{id}', 'VoluntierController#submitStore')->name('voluntier.submit.post');
});

I want to display username of comment's owner, however, comments table has user_id only

After I send the variable that contains the comments to the view, I can only display the user id. This is why I need to somehow foreach through all the comments and based on their user_id to add a new key-pair value with username-username and send it to the view afterwards. Unfortunately, I'm having trouble figuring how to do that.
public function specificImage($id){
$similarImages = null;
$image = Image::with('comments.user')->find($id);
$subImages = Image::where('parent_id', $id)->get();
$views = $image->views;
$image->views = $views + 1;
$image->save();
$authorId = $image->user_id;
$author = User::find($authorId);
$comments = Comment::where('image_id', $id)->get();
$recentImages = Image::where('parent_id', NULL)->where('user_id', $authorId)->orderBy('created_at', 'desc')->limit(9)->get();
$tag = Tag::whereHas('images', function($q) use ($id) {
return $q->where('taggable_id', $id);
})->first();
if (!empty($tag)) {
$tagId = $tag->id;
}
if (!empty($tagId)) {
$similarImages = Image::where('parent_id', NULL)->whereHas('tags', function($q) use ($tagId) {
return $q->where('tag_id', $tagId);
})->orderBy('created_at', 'desc')->limit(9)->get();
}
return view('specificImage', ['image' => $image,'subImages' => $subImages, 'recentImages' => $recentImages, 'similarImages' => $similarImages, 'author' => $author, 'comments' => $comments]);
}
Table:
Table: Comments
Columns: id, user_id, image_id, comment
Image model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
public function tags(){
return $this->morphToMany('App\Tag', 'taggable');
}
public function votes(){
return $this->hasMany('App\Vote');
}
public function comments(){
return $this->hasMany('App\Comment');
}
public function updateVotes()
{
$this->upvotes = Vote::where('image_id', $this->id)->where('vote', true)->count();
$this->downvotes = Vote::where('image_id', $this->id)->where('vote', false)->count();
$this->save();
}
public function updateComments()
{
$this->comments = Comment::where('image_id', $this->id)->count();
$this->save();
}
}
Comment model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function image(){
return $this->belongsTo('App\Image');
}
public function user(){
return $this->belongsTo('App\User');
}
}
User model:
<?php
namespace App;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
class User extends Model implements Authenticatable
{
use \Illuminate\Auth\Authenticatable;
public function images(){
return $this->hasMany('App\Image');
}
public function comments(){
return $this->hasMany('App\Comment');
}
public function votes(){
return $this->hasMany('App\Vote');
}
public function roles(){
return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
}
public function hasAnyRole($roles) {
if (is_array($roles)) {
foreach ($roles as $role) {
if ($this->hasRole($role)){
return true;
}
}
} else {
if ($this->hasRole($roles)){
return true;
}
}
return false;
}
public function hasRole($role){
if ($this->roles()->where('name', $role)->first()){
return true;
}
return false;
}
}
Blade
#extends('layouts.app')
#section('content')
<div class="specific-image-flexbox">
<div class="specific-image-column">
<div class='specific-image-container'>
<img class='specific-image' src='{{url("storage/uploads/images/specificImages/".$image->file_name)}}' alt='Random image' />
#foreach($subImages as $subImage)
<img class='specific-image' src='{{url("storage/uploads/images/specificImages/".$subImage->file_name)}}' alt='Random image' />
#endforeach
</div>
</div>
<div class="artwork-info-column">
<div class="artwork-info-container">
<p class='title'>{{ $image->name }}<p>
<p class='author'>на<a href='{{url("profile/".$author->username )}}'><span class='usernameA artwork-info-username-span'>{{$author->username}}</span></a><img class='artwork-info-profile-picture' src='{{url("storage/uploads/profile_pictures/edited/".$author->profile_picture)}}'></p>
#if(Auth::user())
#if(Auth::id() === $image->user_id || Auth::user()->hasRole('Admin'))
<a class='placeholderDelete' href='{{ route('deleteImage', ['image_id' => $image->id]) }}'><i class="far fa-trash-alt"></i> Изтрий изображението</a>
#endif
#endif
<p class='description'>{{ $image->description }}</p>
<p class='description'>Техника: {{ $image->medium }}</p>
<p><i class="far fa-eye"></i> {{ $image->views }} Преглеждания</p>
<p><i class="far fa-thumbs-up"></i> {{ $image->upvotes }} Харесвания</p>
<p class='commentsCount'><i class="far fa-comments"></i> {{ $image->comments }} Коментари</p>
<a class='downloadImage' href="{{url("storage/uploads/images/specificImages/".$image->file_name)}}" download="{{ $image->name }}"><i class="fas fa-file-download"></i> Изтегли</a>
<!--<a class='placeholderDelete fas fa-expand' href='{{url("storage/uploads/images/specificImages/".$image->file_name)}}'></a>-->
<div class='social-container'>
<div class="addthis_inline_share_toolbox"
data-url="{{ url()->full() }}"
data-title="{{ $image->name }} by {{ $author->username }}"
data-description="{{ $image->description }}"
data-media="{{url("storage/uploads/images/specificImages/".$image->file_name)}}">
</div>
</div>
#if(!empty($recentImages))
#if(count($recentImages) >= 9)
<p class='author'>Още произведения на<a href='{{url("profile/".$author->username )}}'><span class='usernameA artwork-info-username-span'>{{$author->username}}</span></a><img class='artwork-info-profile-picture' src='{{url("storage/uploads/profile_pictures/edited/".$author->profile_picture)}}'></p>
<div class="more-images-container">
#foreach($recentImages as $recentImage)
<div class="more-images-container-element">
<a href='{{url("image/".$recentImage->id)}}'>
<img class='more-images' src='{{url("storage/uploads/images/miniImages/".$recentImage->file_name)}}' alt='Random image' />
</a>
</div>
#endforeach
</div>
#endif
#endif
#if(!empty($similarImages))
#if(count($similarImages) >= 9)
<p class='similar-images'>Подобни произведения</p>
<div class="similar-images-container">
#foreach($similarImages as $similarImage)
<div class="similar-images-container-element">
<a href='{{url("image/".$similarImage->id)}}'>
<img class='more-images' src='{{url("storage/uploads/images/miniImages/".$similarImage->file_name)}}' alt='Random image' />
</a>
</div>
#endforeach
</div>
#endif
#endif
#auth
<div class='postComments'>
<form method='POST' action=''>
<textarea class='comment-section' name='comment'></textarea>
<input type="hidden" name="user_id" value="{{ Auth::user()->id }}">
<input type="hidden" name="image_id" value="{{ $image->id }}">
<button class='postComment submit' type='submit' name='commentSubmit'>Изпрати</button>
</form>
</div>
#endauth
<div class='comments'>
#foreach($image->comments as $comment)
{{ $comment->user->username }}
#endforeach
</div>
</div>
</div>
</div>
<script>
var token = '{{ Session::token() }}';
var urlComment = '{{ route('comment') }}';
var urlLike = '{{ route('vote') }}';
</script>
#endsection
I would suggest adding the user relationship to your Comment model as well:
class Comment extends Model
{
public function image()
{
return $this->belongsTo('App\Image');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
You can then eager load the relationships and then access them in your blade file:
public function specificImage($id)
{
$image = Image::with('comments.user')->find($id);
return view('specificImage', ['image' => $image]);
}
Then in your blade file you would have something like:
#foreach($image->comments as $comment)
{{ $comment->user->username }}
#endforeach

Laravel 5.2 - Delete from db

I am using Laravel Framework version 5.2.45.
I have created a simple view that outputs my todos:
#foreach($todos as $todo)
{{ $todo->todo }} <button href="{{ route('todo.delete', ['id' => $todo->id]) }}" class="btn btn-danger">x</button>
<hr>
#endforeach
Within my routes I have created the following route to delete a todo:
Route::get('/todo/delete/{id}', [
'uses' => 'TodosController#delete',
'as' => 'todo.delete'
]);
Within my TodosController I created the following delete method:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Todo;
class TodosController extends Controller
{
public function delete($id) {
$todo = Todo::find($id);
$todo->delete();
return redirect()->back();
}
// ...
When I press the button in the frontend nothing happens. I do not get any error...
Any suggestions what is wrong with my implementation?
Appreciate your replies!
You are using button not tag
turn your code from
#foreach($todos as $todo)
{{ $todo->todo }} <button href="{{ route('todo.delete', ['id' => $todo->id]) }}" class="btn btn-danger">x</button>
<hr>
#endforeach
to
#foreach($todos as $todo)
{{ $todo->todo }} x
<hr>
#endforeach
Try Below code, You have used a button instead of a tag
#foreach($todos as $todo)
{{ $todo->todo }} x
<hr>
#endforeach
You should do like this :
Delete Button :
<a class="btn btn-primary" href="{{ route('todo.delete',$todo->id) }}">Delete</a>
And delete function look like below :
public function delete($id) {
try {
$delete_flag = Todo::where(['id' => $id])->first();
$delete_flag->delete();
return redirect()->back()->with('success', 'Todo deleted successfully');
} catch (Exception $ex) {
return redirect()->back()->with('error', 'Something went wrong');
}
}
#foreach($todos as $todo)
{{ $todo->todo }} x
#endforeach
delete code--
$toDo = Todo::findOrFail($id)->delete();
if($toDo){
return response()->josn(['message'=>'deleted']);
}

Categories