Laravel Multi Select with Select2 Ajax - laravel

I implemented a Many To Many relation between Posts and Tags. I am using Select2 Ajax for Multi Select and html is rendered by the Spatie/HTML package.
In the create form, I can select the tags and while i same the database table updates successfully. I can also show the tags.
I am facing an issue in the edit form. I am using the same create form for the edit and though the Tags has been attached earlier i can not see those as selected. What is the solution of this. Some of the codes are mentioned below.
Form
{{ html()->multiselect('tags_list', '', $posts->tags->pluck('id')->toArray())->class('form-control select2-tags')) }}
Model:
public function tags()
{
return $this->belongsToMany('App\Models\Tag');
}

The following code works, but is there any better solution? may be via Model?
{{ html()->multiselect('tags_list', $posts->tags->pluck('name', 'id'), $posts->tags->pluck('id')->toArray())->class('form-control select2-tags')) }}

Related

Laravel view into another view

Just started learning Laravel not long ago and I've got a question about views.
I have a 2 view files (blade).
The one which shows the categories from database.
The other one is showing the results of as search in products.
I'd like to use them in the same view, in the first section would be the searcher area and the area below is where I would like to list the categories.
I tried a couple of things to make it work, but I'm not sure which is the right approach:
I made a function in a controller where I listed the categories and handled the search and sent that to the view, but i didn't like this approach because I'm handling two different logic in one function.
I tried to yield or #include the view file into the main view. I got an error, because the database query didn't happen that case. I think yield and include only available with static data.
So, I'm don't know how to handle that issue properly.
Can someone suggest me a solution for this problem?
Thanks the help in advance!
There can be several way.
You can try to fetch category data inside blade file.
So, for example, in category.blade, you can fetch category list from database.
Then it would be independent to other views file and controllers.
And you can include category.blade.php for example.
The second way, is to fetch category data via ajax.
In this case, you can not insert script in all pages of using category.
So, in this case, you can use template structure.
For example.
In template.blade.php
<!DOCTYPE html>
<html class="no-js css-menubar" lang="en">
#stack('style')
#include('admin.layouts.head')
#include('admin.layouts.header')
#include('admin.layouts.page')
#include('admin.layouts.footer')
#stack('script')
</html>
In page.blade.php
<div class="page">
#yield('page-content')
</div>
In individual page,
#extends('admin.layouts.template' ,['menu'=>'coach'])
#section('insert-css')
your custom css content here
#endsection
#section('page-content')
Your page content here
#endsection
You must get $categories just once and pass $categories to all views (or views that need to category or just pass it to categories.blade.php).
for this goal, I suggest that create a partial blade called categories.blade.php and show all cateogories in it and include it wherever necessary, but before before that go to app/Provider/AppServiceProvider.php and in boot() method get categories and share it in categories blade that you created it, like below :
public function boot() {
// pass to first param, address categories blade
View()->composer('categories', function ($view){
// set a name for variable that get it in categories view
$view->with(['categories'=>$categories]);
});
}
If you would like to know more about subscriptions, visit this link or Laravel docs

How to dynamically load/render Laravel Collective form?

I'm devising a small CMS for the in-house development team, where all have experience working with laravel.
The CMS requires a small feature where the services that are listed can have a quotation form attached. Instead of creating a completely separate module to add elements & other separately, I wanted to have the system in a manner that the developer adds the laravel collective form code, which we store in the database.
While retrieving, we render the form server side.
Here's my implementation
Controller
public function show($id)
{
$data['page'] = Service::where('slug', $id)->first();
if ($data['page']) {
....
$data['form'] = $data['page']->quoteform()->first();
....
And in the view
{!! $form['html'] !!}
But this is definitely won't help, so I tried this approach of rendering the collective form
$data['form'] = View::make('website.includes.render-form',['form'=>$data['page']->quoteform()->first()]);
But I'm not sure if this should work, as I couldn't make it work.
Looking forward to a solution if at all the approach I choose is possible, if yes or can be done, would like to know more on the same.
TIA
Edit 1:
I used the following blade command Blade::compileString('string here') which helped to a certain extent.
where I'm getting the following result
You can render the HTML of a view using render() method. So you can update to this :
$data['form'] = View::make('website.includes.render-form',
['form' => $data['page']->quoteform()->first()]
)->render();
Now the $data['form'] will have rendered HTML which you can use in blade using {!! $data['html'] !!} if you are passing $data to your main view.

Directly access a put/update method on Laravel 5.1 without going into the edit view (MethodNotAllowedHttpException in RouteCollection.php error)

I wanted to disable employees from a button on my index.blade.php page. Currently, the options of disabling employees (setting the status column in the database to false) is either to have an edit.blade.php view and update the value there, which is pretty standard for any laravel app or to have a new view for example, changestatus.blade.php, with the proper routes offcourse and update the value there. I am using the second implementation and it's working perfectly.
What i wanted to implement is to have a button on the index page which will change the status of the employee without going to a edit.blade.php or changestatus.blade.php page.
What i have tried
I have created new routes and created a button to link to the changestatus function
Routes.php
Route::put('employees/{employee}/changestatus', 'EmployeesController#changestatus')->name('employees.changestatus');
Route::resource('employees', 'EmployeesController');
EmployeeController
public function changestatus($EmployeeID)
{
$employee = Employee::find($EmployeeID);
$employee->status = true;
$employee->Save();
}
On my view i created a button with the following link
{{ URL::route('employees.changestatus', $employee->EmployeeID) }}
When i click that link, i get the MethodNotAllowedHttpException in RouteCollection.php error.
I even tried to change the Route::put to Route::Patch, but it's the same thing.
Is it even possible to achieve what I'm trying to do? If so, how?
When you click on a hyperlink, the web browser submits a GET request. Your route has been defined as being a PUT so that's why you're getting an exception.
You could either change the route to a GET by defining it like this:
Route::get('employees/{employee}/changestatus', 'EmployeesController#changestatus')->name('employees.changestatus');
Which isn't very ReSTful since a GET request should really only be used for returning a resource rather than modifying it.
Or, you could modify the button so that it submits a form like this:
<form method="post" action="{{ route('employees.changestatus', $employee->EmployeeID) }}">
{{ method_field('PUT') }}
<button type="submit">Button Text</button>
</form>
Note that you can't simply set the form method to PUT since this method isn't generally supported by web browsers. Laravel supports method spoofing which you can read all about here:
http://laravel.com/docs/5.1/routing#form-method-spoofing

Laravel 5 - getting data to a view

I think this is slightly different to the usual controller passing data to the view. I have a Project which has one DocumentOne. Within my app, the user creates a Project. This then redirects them to the show page for this project.
So with the project created, and the user on the show page for that project, I display the project ID. I then provide a select menu where the user can select a Document to display. So say I am in Project with the ID of 1, I then decide to show DocumentOne for this project. This displays a form with inputs for DocumentOne.
When the user fills in the form and submits, the data is saved to the database. The Project ID is the foreign key for DocumentOne. The following route is set up for DocumentOne
Route::resource('projects.documentOne', 'DocumentOneController');
Now I have data for DocumentOne which is linked to the Project with an ID of 1. However, if I now go back to the projects show page and then select Document One from the dropdown again, all I see is an empty form. This is obviously because the controller for this is
public function show(Project $project)
{
return view('projects.show', compact('project'));
}
So I am never passing it data for DocumentOne because theoretically it is not created when the Project is first shown. What I want to do is when the Document is selected in the Projects show page, is to have the form populated with whatever is in the database for that Document. If nothing is in the database, then the form will be empty. I have a DocumentOne Controller, but I dont know if I can link this to the Projects show page. I was thinking about doing something like this in the DocumentOne controller
public function show(DocumentOne $documentOne)
{
return view('projects.show', compact('documentOne'));
}
But not sure this will work. Hope I have not been too confusing and you understand what I am attempting, hoping someone can offer advice on how best to handle this situation.
Thanks
In my previous project, I also deal with such requirement, I thought so. Here my solution to solve such requirement.
Actual code calling from ajax.
Routes
get('setFlashData',function(Request $request){
$final_response = array();
$data_information = $request->except('_token');
$request->session()->flash('cmg_quick_create_data', $data_information);
if($request->session()->has('cmg_quick_create_data')){
$final_response['result']['success'] = true;
}
return response()->json($final_response);
});
But according to you requirement:
$data_information = $request->except('_token');
$request->session()->flash('cmg_quick_create_data', $data_information);
My basic functionality was, to share form data from Quick Create Section which is pop-up form to Full create form section, and whenever user click to "Go To Full Form" button from pop up, ajax call mentioned function which will set the flash data and than on destination side I only check weather its contain the flash data or not. and deal according to data.
#if (Session::has('cmg_quick_create_data')) {
{!! Form::model(Session::get('cmg_quick_create_data'),["class"=>"form-horizontal","data-parsley-validate"=>"data-parsley-validate",'role'=>'form','files'=>true]) !!}
#else
{!! Form::open(["class"=>"form-horizontal","data-parsley-validate"=>"data-parsley-validate",'role'=>'form','files'=>true]) !!}
#endif
I can understand this solution might be different from you requirement but hope full to figure out your solution. Look forward to hearing from you if still unclear from my side.

How to display the query result without reloading the page?

I want to show my users data from my mysql database without reloading the page.
I am using Codeigniter. I have a dropdown menu like the following, - when the page loads I want it to show all data by default. But when any user selects any name it will query to database and show results immediately without having the page reloaded.
I already have a controller, model and view to display all data from database but I don't know how to get the dropdown menu work after a person has selected a value, to fetch data from database and show immediately without reloading the page.
I have some basic knowledge of PHP but I have no idea about AJAX. Would you please kindly give me an example or idea on how to do this?
I am not expecting you to write the code for me, I am just asking for an example or a guideline. :)
Thanks in Advance.
<form>
<select name="info">
<option value="">Select a person:</option>
<option value="11080101">John</option>
<option value="11080102">Bon Jovi</option>
</select>
</form>
It sounds like with what you are aiming to achieve this isn't really a codeigniter related question but more a HTML, JQUERY question.
Using jQuery To Manipulate and Filter Data over at Net-tuts shows a jquery solution to sorting and filtering data. Their solution is based on a table but the principals are there so a modification can get it to do what you want it to do.
well i can give you the flow of how can you try it
trigger a jquery event on selecting an dropdown menu item. if you don't have any idea how to do it try reading the documentation of jquery for using selectors .
once you have the selected element , extract its value and send an ajax call to your path
like this (for jquery ajax visit jqapi it has all the documentation for jquery ajax functions and its derivatives)
$.post('/user/data/' + id , function(response) {
console.log(response)
})
or
$.post('/user/data/', 'id=' + id , function(response) {
console.log(response)
})
and now you have your data in reponse so you can do whatever you wish to do with it

Resources