How to insert (create) data (CRUD) FORM in blade in multiple languages into database and read it out with LARAVEL MULTILANGUAGE - LOCALIZE? - laravel

I have followed this tutorial (https://mydnic.be/post/how-to-build-an-efficient-and-seo-friendly-multilingual-architecture-for-your-laravel-application) about laravel multilanguage and localization. Everything seems ok, except I want to CREATE a CRUD for inserting this posts with title and content in multiple language - and STORE it in database - and then read it out in index blade.
Can you show me an example of CRUD in this way in blade for CREATE and in Controller for CREATE and STORE function. How to make this to work?
This is my simple main CRUD, how to extend this to be able to creating and storing into multiple language when creating.
And how to extend the controller for storing in multiple language when using this translatable package from tutorial above (link).
CRUD:
<form method="POST" action="/posts">
#csrf
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" name="title">
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea id="content" name="content" class="form-control"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Publish</button>
</div>
</form>
CONTROLLER
public function store(Request $request)
{
$post = Post::all();
$this->validate(request(), [
'title' => 'required',
'content' => 'required'
]);
$post = new Post;
$post->title = $request->title;
$post->content = $request->content;
$post->save();
return redirect('/');
THANKS :)

I'm the author of the tutorial.
The whole point of that implementation is that you don't have to worry about the model locale at all. The locale is set through the URL "/en/..."
So if you make a POST request to your model store URL like so :
POST /en/post {payload}
The App Locale of your laravel application will be automatically set before you even reach the PostController#store method.
Then, you can simply create your model like you would usually do (like in your exemple, that's correct) , and the model will be stored with the according locale.
Now that your model is initially created with the defined locale, you should be able to edit it in another language.
So you can go to this URL: /en/post/:id/edit then switch to another locale : /fr/post/:id/edit and you will notice that all input of the translatable fields are blank. That's normal because the 'fr' translation of that model doesn't exist yet.
You can thus fill the form with the 'fr' translated field, then save (update the model). And the translation will be saved. Your model is now translated :)
Hope this helps !
PS you can have a look at the example code here https://github.com/mydnic/Laravel-Multilingual-SEO-Example

So based on the tutorial, you'll have a column in your posts table called locale
Then in your view, you can add a select field from which you can chose the locale
<div class="form-group">
<label for="locale">Locale</label>
<select id="locale" name="locale" class="form-control">
<option value="en">English</option>
<option value="fr">French</option>
</select>
</div>
Then in your controller add the following line:
$post->locale = $request->locale;
Put locale in your $fillable array within the post model.

THIS IS WORKING WELL IN THIS SITUATION:
CONTROLLER:
public function create()
{
return view('services.new');
}
public function store(Request $request)
{
$service = new Service();
$service->save();
$this->validate($request, [
'title2' => 'required|max:350',
'content2' => 'required'
]);
foreach (['en', 'bs'] as $locale) {
$service->translateOrNew('en')->title = $request->title;
$service->translateOrNew('en')->content = $request->content;
$service->translateOrNew('bs')->title = $request->title2;
$service->translateOrNew('bs')->content = $request->content2;
}
$service->translateOrNew('en')->title = $request->title;
$service->translateOrNew('en')->content = $request->content;
$service->translateOrNew('bs')->title = $request->title2;
$service->translateOrNew('bs')->content = $request->content2;
// $article->translateOrNew('en')->text = ['texten'];
// $article->translateOrNew('ka')->name = ['nameka'];
// $article->translateOrNew('ka')->text = ['textka'];
// return $article;
// exit();
$service->save();
return redirect()->back();
}
BLADE FOR CREATE + CSS (in background):
<form action="{{route('service.store')}}" method="POST">
{{csrf_field()}}
<div class="tabset">
<!-- Tab 1 -->
<input type="radio" name="tabset" class="radio1" id="tab1" aria-controls="marzen" checked>
<label for="tab1">Bosanski</label>
<!-- Tab 2 -->
<input type="radio" class="radio1" name="tabset" id="tab2" aria-controls="rauchbier">
<label for="tab2">Engleski</label>
{{-- <!-- Tab 3 -->
<input type="radio" name="tabset" id="tab3" aria-controls="dunkles">
<label for="tab3">Dunkles Bock</label> --}}
<div class="tab-panels">
<section id="marzen" class="tab-panel">
<h2>Dodaj novu uslugu</h2>
<div class="form-group">
<lebal>Naslov*(bs)</lebal>
<input type="text" class="form-control" name="title2">
</div>
<div class="form-group">
<lebal>Opis*(bs)</lebal>
<textarea class="form-control" name="content2"></textarea>
</div>
</section>
<section id="rauchbier" class="tab-panel">
<h2>Dodaj novu uslugu</h2>
<div class="form-group">
<lebal>Title (EN)</lebal>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<lebal>Description (EN)</lebal>
<textarea class="form-control" name="content"></textarea>
</div>
</section>
<section id="dunkles" class="tab-panel">
<h2>Tab3</h2>
</section>
</div>
<input type="submit" value="Submit">
</form>
WEB.PHP:
Route::post('/create',[
'uses' => 'ServicesController#store',
'as' => 'service.store'
]);

Related

Form Won't Pass Value Pair In Get Request Url After Submission

I'm familiarizing myself with API's Get & Post Request in Laravel. I have a form where an admin can send Points to an external API. Unfortunately, in the documentation the request has to be a GET request and the data which is being submitted has to append to the url
ie: myurl.com/my-end-point?platform_id=value&auth=value...
The issue is, whenever i fill the form and submit the url remains the same:
ie: myurl.com/my-end-point?platform_id=platform_id&auth=auth...
It does not pass the data in the get request.
Controller
public function sendCpdPoints(Request $request)
{
$response = Http::asForm()->get('myurl.com/my-end-point', [
'platform_id' => 'platform_id',
'auth' => 'auth',
'cpd_id' => 'cpd_id',
'registration_number' => 'registration_number',
'certificate' => 'certificate',
]);
dd($response);
}
View (Blade)
<form action="{{url('admin/rewards/points/manual_update/dashboard/store/participants-points') }}" method="POST">
<div class="modal-body">
{{ csrf_field() }}
<div class="form-group">
<label>Platform Id</label>
<input type="text" name="platform_id" id='platform_id' class="form-control" value="123" readonly>
</div>
<div class="form-group">
<label>Authentication Key</label>
<input type="text" name="auth" id='auth' class="form-control" value="123456789" readonly>
</div>
<div class="form-group">
<label>Cpd Id</label>
<input type="text" name="cpd_id" id='cpd_id' class="form-control" placeholder=".ie 587">
</div>
<div class="form-group">
<label>Registration Number</label>
<input type="text" name="registration_number" id='registration_number' class="form-control" placeholder=".ie MDC/PA/RNXXXX">
</div>
<div class="form-group">
<label>Certificate Serial Number</label>
<input type="text" name="certificate" id='certificate' class="form-control" placeholder=".ie 2022-03/001">
</div>
<button type="send" class="btn btn-primary">Send</button>
</div>
</form>
Help is greatly appreciated. As i really want to get better.
You need to pass the value from the form . You can use $request-> from the request facade
You can try this
public function sendCpdPoints(Request $request)
{
$response = Http::asForm()->get('myurl.com/my-end-point', [
'platform_id' => $request->platform_id,
'auth' => $request->auth,
'cpd_id' => $request->cpd_id,
'registration_number' => $request->registration_number,
'certificate' => $request->certificate,
]);
dd($response);
}
Let me see if I understand. Does your backend that handles the request call an external API? If that's the case, the problem is that you're passing strings as an argument. To retrieve the form values try something like:
$request->auth or
$request->get('auth')
If this is not the case, and you simply want to get the form data in your backend, I advise you to do it with JS using AJAX. You can use Fetch or install an external lib like axios to do this.
NOTE: the type of your submit button is incorrect, change it to type="submit"
https://www.w3schools.com/tags/att_button_type.asp

PUT/POST in Laravel

I'm brand new to Laravel and am working my way through the [Laravel 6 from Scratch][1] course over at Laracasts. The course is free but I can't afford a Laracasts membership so I can't ask questions there.
I've finished Section 6 of the course, Controller Techniques, and am having unexpected problems trying to extend the work we've done so far to add a few new features. The course has students build pages that let a user show a list of articles, look at an individual article, create and save a new article, and update and save an existing article. The course work envisioned a very simple article containing just an ID (auto-incremented in the database and not visible to the web user), a title, an excerpt and a body and I got all of the features working for that, including updating an existing article and saving it.
The update form sets method to POST but then uses a #METHOD('PUT') directive to tell the browser that it is actually supposed to do a PUT. This worked perfectly in the original code. However, now that I've added two more fields to the form, when I click Submit after editing an existing record, the save fails with this message:
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The PUT method is not supported for this route. Supported methods: GET, HEAD, POST.
http://localhost:8000/articles
I don't understand why adding two fields to the form would cause this to break. Can someone enlighten me? I added the two new fields/columns to the migration and ran migrate:rollback and migrate. I've also added the new fields/columns to the fillable attribute and added validations for them in the ArticlesController.
Here is my routing:
Route::get('/articles', 'ArticlesController#index');
Route::post('/articles', 'ArticlesController#store');
Route::get('/articles/create', 'ArticlesController#create');
Route::get('/articles/{article}', 'ArticlesController#show');
Route::get('/articles/{article}/edit', 'ArticlesController#edit');
Route::put('/articles/{article}', 'ArticlesController#update');
//Route::delete('/articles/{article}', ArticlesController#destroy');
This is my ArticlesController:
<?php
namespace App\Http\Controllers;
use App\Article;
use Illuminate\Http\Request;
class ArticlesController extends Controller
{
public function index()
{
$articles = Article::latest()->get();
return view ('articles.index', ['articles' => $articles]);
}
public function show(Article $article)
{
return view('articles.show', ['article' => $article]);
}
public function create()
{
return view('articles.create');
}
public function store()
{
//Stores a NEW article
Article::create($this->validateArticle());
return redirect('/articles');
}
public function edit(Article $article)
{
return view('articles.edit', ['article' => $article]);
}
public function update(Article $article)
{
//Updates an EXISTING article
$article->update($this->validateArticle());
return redirect('/articles/', $article->id);
}
public function validateArticle()
{
return request()->validate([
'title' => ['required', 'min:5', 'max:20'],
'author' => ['required', 'min:5', 'max:30'],
'photopath' => ['required', 'min:10', 'max:100'],
'excerpt' => ['required', 'min:10', 'max:50'],
'body' => ['required', 'min:50', 'max:500']
]);
}
public function destroy(Article $article)
{
//Display existing record with "Are you sure you want to delete this? Delete|Cancel" option
//If user chooses Delete, delete the record
//If user chooses Cancel, return to the list of articles
}
}
Here's my edit form, edit.blade.php:
#extends('layout')
#section('content')
<div id="wrapper">
<div id="page" class="container">
<h1>Update Article</h1>
<form method="POST" action="/articles">
#csrf
#method('PUT')
<div class="form-group">
<label class="label" for="title">Title</label>
<div class="control">
<input class="form-control #error('title') errorborder #enderror" type="text" name="title" id="title" value="{{ $article->title }}">
#error('title')
<p class="errortext">{{ $errors->first('title') }}</p>
#enderror
</div>
</div>
<div class="form-group">
<label class="label" for="author">Author</label>
<div class="control">
<input class="form-control #error('author') errorborder #enderror" type="text" name="author" id="author" value="{{ $article->author }}">
#error('title')
<p class="errortext">{{ $errors->first('author') }}</p>
#enderror
</div>
</div>
<div class="form-group">
<label class="label" for="photopath">Path to Photo</label>
<div class="control">
<input class="form-control #error('photopath') errorborder #enderror" type="text" name="photopath" id="photopath" value="{{ $article->photopath }}">
#error('title')
<p class="errortext">{{ $errors->first('photopath') }}</p>
#enderror
</div>
</div>
<div class="form-group">
<label class="label" for="excerpt">Excerpt</label>
<div class="control">
<textarea class="form-control #error('excerpt') errorborder #enderror" name="excerpt" id="excerpt">{{ $article->excerpt }}</textarea>
#error('excerpt')
<p class="errortext">{{ $errors->first('excerpt') }}</p>
#enderror
</div>
</div>
<div class="form-group">
<label class="label" for="body">Body</label>
<div class="control">
<textarea class="form-control #error('body') errorborder #enderror" name="body" id="body">{{ $article->body }}</textarea>
#error('body')
<p class="errortext">{{ $errors->first('body') }}</p>
#enderror
</div>
</div>
<div class="control">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</form>
</div>
</div>
#endsection
Is there anything else you need to see?
[1]: https://laracasts.com/series/laravel-6-from-scratch/episodes/33?autoplay=true
Your Laravel route is:
Route::put('/articles/{article}', 'ArticlesController#update');
So your form action url should match that uri:
<form action="{{ url('/articles/'.$article->id) }}">
where the {article} parameter is the record id (you can read more about in the docs here).
Then in your controller update() method, you have:
return redirect('/articles/', $article->id);
which means redirect to /articles with status code $article->id (you can read more about in the docs here). I think you are trying to redirect to the show route, which is:
Route::get('/articles/{article}', 'ArticlesController#show');
So change the , (comma) to a . (dot) to concatenate the article id with the uri:
return redirect('/articles/' . $article->id);
The route in the form for /articles, However your route for updating should be /articles/{article}
Try this:
<form method="POST" action="/articles/{{ $article->id }}">

Laravel 5.7 using same url action for insert and update with #yield in blade template

I am using laravel 5.7 and I am using one form for inserting and updating. In form action I want to use #yield() for laravel route to get the id for updation. Every thing is fine but I can't use #yield() method. Here is my code, problem is only in action of the form.
<form class="form-horizontal" action="{{ url('/todo/#yield('editId')') }}" method="post">
{{csrf_field()}}
#section('editMethod')
#show
<fieldset>
<div class="form-group">
<div class="col-lg-10">
<input type="text" name="title" placeholder="Title" value="#yield('editTitle')" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<textarea class="form-control" placeholder="Body" name="body" rows="5" id="textarea">#yield('editBody')</textarea>
<br>
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</fieldset>
</form>
I have also checked with single and double quotes.
action="/todo/#yield('editid')"
When I use simple this method then after submitting it redirects me to localhost and with an error page not found. In laravel 5.4 it works. but not in laravel 5.7. Any help would be appreciated Thanks
Here is my edit.blade.php from where I am using the #section and #yield
#extends('Todo.create')
#section('editId',$item->id)
#section('editTitle',$item->title)
#section('editBody',$item->body)
#section('editMethod')
{{ method_field("PUT") }}
#endsection
Controller store edit and update methods are
public function store(Request $request)
{
$todo = new todo;
$this->validate($request,[
'body'=>'required',
'title'=>'required|unique:todos',
]);
$todo->body = $request->body;
$todo->title = $request->title;
$todo->save();
return redirect("todo");
}
public function edit($id)
{
$item = todo::find($id);
return view("Todo.edit",compact('item'));
}
public function update(Request $request, $id)
{
$todo = todo::find($id);
$this->validate($request,[
'body'=>'required',
'title'=>'required',
]);
$todo->body = $request->body;
$todo->title = $request->title;
$todo->save();
return redirect("/todo");
}
To answer the OP actual question you would need to do
#section('editId', "/$item->id") or #section('editId', '/'.$item->id')
{{ url('/todo') }}#yeild('editId')
But much better to do
{{ url('/todo/'.(isset($item) ? $item->id : '')) }}
Or for PHP >= 7
{{ url('/todo/'.($item->id ?? '')) }}
As apokryfos already mentioned - #yield is thought to make reusing your templates easier.
If you simply want to determine (for example) which action should be called afterwards you should better do something like that:
#extends('Todo.create')
<form class="form-horizontal" action="/todo/{{ isset($item) ? $item->id : '' }}" method="post">
#if( ! isset($item))
{{ method_field("PUT") }}
#else
{{ method_field("PATCH") }}
{{csrf_field()}}
<fieldset>
<div class="form-group">
<div class="col-lg-10">
<input type="text" name="title" placeholder="Title" value="{{ isset($item) ? $item->title : '' }}" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<textarea class="form-control" placeholder="Body" name="body" rows="5" id="textarea">{{ isset($item) ? $item->body : '' }}</textarea>
<br>
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</fieldset>
</form>
Also as I remember the method field should always come first to make sure it's recognized correctly. Additionally you shouldn't need url() to generate the url I think.
No need for a second blade. Simply inject the variables directly into the template and make sure they are set before you access them. I didn't try it but I'd think that it should work.

Multi-criteria search in Symfony 3.4

I'm finally working on a project in Symfony 3 and it's really very interesting. I encounter new problems and new questions that I want to share with you.
I work on a search form for publications according to several criteria. (I have 3 fields input text: date, category and keyword).
So I handle publication consisting of a date of creation, linked to a category by oneToMany relation [Publication is the entity owning, each publication to a single category] and having several several Tag [there is a ManyToMany relationship with the Tag entity. The search form allows to search by dateCreation, Category and Tag. On the right of the publication list I have a form to perform the search.
<div>
<span class="titlerecherche">recherche</span>
<div class="formrecherch">
<form action="{{ url('search_english_pub') }}" method="POST" class="form-horizontal" role="form" data-parsley-validate novalidate>
<div class="form_row">
<div class="col-xs-12 col-sm-12">
<input type="text" class="input" name="date" placeholder="Date *" required></div>
</div>
<div class="form_row">
<div class="col-xs-12 col-sm-12"><input type="text" name="categorie" class="input" placeholder="Catégorie *" required></div>
</div>
<div class="form_row">
<div class="col-xs-12 col-sm-12"><input type="text" name="tag" class="input" placeholder="Tag *" required></div>
</div>
<button class="btnForm">Envoyer <i class="icon-long-arrow-right"></i></button>
</form>
</div>
</div>
In my entity I have:
enter image description here
If only you could edit question and provide more details so i can help more
in the mean time try this:
public function searchAction(Request $request)
{
$date = $request->request->get('date');
$category = $request->request->get('category');
$keyword = $request->request->get('keyword');
$em = $this->getDoctrine()->getManager();
$listEnglishs = $em->getRepository('MDWEBInEnglishBundle:InEnglish')
->findBy(array("date" => new \DateTime($date), "category" => $category, "keyword" => $keyword));
return $this->render('MDWEBFrontBundle:InEnglish:list.html.twig',
array('listEnglishs' => $listEnglishs));
}
also add this at the top
use Symfony\Component\HttpFoundation\Request;

not getting checkbox element value from form

I have a small form in Laravel 5.4 which has a checkbox and a text box. The issue is that when I post the form, the checkbox value is not coming through the request. I have custom styling on the checkbox but surely it can't be that?
I've been looking at this for a while, and everything looks normal. My code is below:
<form method="post" action="{{ route('admin.settings.save') }}">
{{ csrf_field() }}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label><b>Site Name</b></label>
<p>This is the name of your LaravelFileManager instance.</p>
<input name="siteName" id="siteName" class="form-control" value="{{ \App\Helpers\ConfigHelper::getValue('site_name') }}" />
</div>
<div class="form-group">
<label><b>Footer Message</b></label>
<p>You can customise the footer message for the application.</p>
<div class="checkbox">
<label>
<input type="checkbox" name="showFooter" id="showFooter" checked="{{ \App\Helpers\ConfigHelper::getValue('show_footer_message') }}"> Show footer message
</label>
</div>
</div>
<button type="submit" class="btn btn-success"><i class="fa fa-save"></i> Save Changes</button>
</div>
</div>
</form>
My controller code is as such:
public function saveSettings(Request $request) {
$siteName = $request->input('siteName');
$showFooter = $request->input('showFooter');
ConfigHelper::setValue('site_name', $siteName);
ConfigHelper::setValue('show_footer_message', $showFooter);
return redirect()->route('admin.settings')->with('result', 'Settings saved.');
}
My route:
Route::post('settings/save', ['uses' => 'Admin\SettingsController#saveSettings'])->name('admin.settings.save');
I've also done a vardump on the $request variable and even that is missing the check box value:
array(2) {
["_token"]=> string(40) "sgyO7Kkz1ljsYEZ1G5nkj4uVbmFZqiTMbpK9P6Bi"
["siteName"]=> string(16) "File Manager 1.0"
}
It's missing the 'showFooter' variable.
Not quite sure where to go with this one. Any help appreciated.
So I got this working in the end. Using help from the comments:
public function saveSettings(Request $request) {
$siteName = $request->input('siteName');
$showFooter = $request->has('showFooter');
ConfigHelper::setValue('site_name', $siteName);
ConfigHelper::setValue('show_footer_message', $showFooter);
return redirect()->route('admin.settings')->with('result', 'Settings saved.');
}
For some reason, using $request->input('showFooter') wasn't working properly. $request->get('showFooter') brings a result when true, so adding the ternary makes it work every time.

Resources