I am working on a project with symfony 3 and I want to dynamically get a list of users from database by the name of the project they are working on.
This is the controller action:
This way it doesn't show anything, it only shows the first user if I write the action this way:
If I do understand it right, you have a page where you have an AJAX request which shall return some data already rendered with twig.
What you need to do is:
One controller which returns normal HTML page
A second controller which returns your rendered data same as your first controller does, but this one uses a template which contains only the HTML which will be returned by the AJAX request.
In your AJAX request call the route defined in the second controller and display the result.
Example1:
ControllerOne.php:
class ControllerOne extends Controller
{
/**
* #Route("/")
* #return \Symfony\Component\HttpFoundation\Response
*/
public function indexAction()
{
// show your page
return $this->render('index.html.twig');
}
}
ControllerTwo.php:
class ControllerTwo extends Controller
{
/**
* #Route("get/data/{userId}")
* #param $userId
* #return \Symfony\Component\HttpFoundation\Response
*/
public function getDataAction($userId)
{
// get some data
$em = $this->getDoctrine()->getManager();
// this example shows retrieving user data
// implement your logic for retrieving projecty by user id here
$userData = $em->getRepository('AppBundle:User')->findOneBy(array('id' => $userId));
return $this->render('user.data.html.twig', array('user' => $userData));
}
}
index.html.twig:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="application/javascript">
// call the controller to get the rendered data
$.ajax({
url: "/get/data/1"
})
.done(function( data ) {
// insert data into div
$("#myDiv").html(data);
});
</script>
</body>
</html>
user.data.html.twig:
<div>
<p>
<!-- you have access to the data passed from controller here -->
User name: {{user.name}}
</p>
</div>
Example2:
JsonResponseController.php:
class JsonResponseController extends Controller
{
/**
* #Route("get/data/{userId}")
* #param $userId
* #return \Symfony\Component\HttpFoundation\Response
*/
public function getDataAction($userId)
{
// get some data
$em = $this->getDoctrine()->getManager();
// this example shows retrieving user data
// implement your logic for retrieving projecty by user id here
$userData = $em->getRepository('AppBundle:User')->findOneBy(array('id' => $userId));
return new JsonResponse(array('userData' => $userData));
}
}
Related
My Route
Route::put('dataedit/{id}', [empDataController::class, 'empDataEdit'])->middleware('guest')->name('emp.data.edit');
My Controller
public function empDataEdit(empDataValidation $request, $id){
$id = Crypt::decrypt($id);
$DataAddCheck = EmpData::find($id)->update($request->all());
if($DataAddCheck){
return back()->with('successMsg', 'Data Added Successfully');
}
else{
return back()->with('successMsg', 'Something Went Wrong Try Again!');
}
}
Note : I add use App\Http\Requests\empDataValidation; in controller Top.
My Request Validation
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class empDataValidation extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'empName' => ['required'],
];
}
}
My blade (Just Important part)
<form id="msform" method="post" enctype="multipart/form-data"
action="{{ route('emp.data.edit', Crypt::encrypt($data->id)) }}">
#csrf
#method('PUT')
Note: When I use Request $request in controller It works Fine but when I use empDataValidation $request It not working, In my create controller empDataValidation $requestworks fine. Please help to solve this issue.
I was following this guide to show all partners in my admin section: https://yajrabox.com/docs/laravel-datatables/master/quick-starter
Unfortunately, there are no errors, but I don't see also the list with all items. There are results in the database, but for me, it seems it is not making the query, that's why there are no results (in the debuggbar i don't see a query with the 'partners' table).
route.php
Route::get('partners', [PartnerController::class, 'index'])->name('partners.index');
PartnerController:
namespace App\Domains\Partner\Http\Controllers\Backend;
use App\Domains\Partner\DataTable\PartnersDataTable;
use App\Domains\Partner\Models\Partner;
use App\Domains\Partner\Services\PartnerService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class PartnerController extends Controller
{
public function index(PartnersDataTable $dataTable)
{
return $dataTable->render('backend.partner.index');
}
}
PartnersDataTable:
namespace App\Domains\Partner\DataTable;
use App\Domains\Partner\Models\Partner;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;
class PartnersDataTable extends DataTable
{
/**
* Build DataTable class.
*
* #param mixed $query Results from query() method.
* #return \Yajra\DataTables\DataTableAbstract
*/
public function dataTable($query)
{
return datatables()
->eloquent($query);
}
public function query(Partner $model)
{
return $model->newQuery();
}
/**
* Optional method if you want to use html builder.
*
* #return \Yajra\DataTables\Html\Builder
*/
public function html()
{
return $this->builder()
->setTableId('partners-table')
->columns($this->getColumns())
->minifiedAjax()
->dom('Bfrtip')
->orderBy(1)
->buttons(
Button::make('create'),
Button::make('export'),
Button::make('print'),
Button::make('reset'),
Button::make('reload')
);
}
/**
* Get columns.
*
* #return array
*/
protected function getColumns()
{
return [
Column::make('id'),
Column::make('title'),
];
}
/**
* Get filename for export.
*
* #return string
*/
protected function filename()
{
return 'Users_' . date('YmdHis');
}
}
index.blade.php:
#extends('backend.layouts.app')
#section('title', __('Partners'))
#section('breadcrumb-links')
#endsection
#section('content')
<x-backend.card>
<x-slot name="header">
#lang('Partners')
</x-slot>
#if ($logged_in_user->hasAllAccess())
<x-slot name="headerActions">
<x-utils.link
icon="c-icon cil-plus"
class="card-header-action"
:href="route('admin.partners.create')"
:text="__('Create partner')"
/>
</x-slot>
#endif
<x-slot name="body">
{!! $dataTable->table() !!}
</x-slot>
</x-backend.card>
#endsection
#push('after-scripts')
<script src="{{ asset('vendor/datatables/buttons.server-side.js') }}"></script>
{{$dataTable->scripts()}}
#endpush
Here is what is $dataTable->scripts() producing:
<script src="http://kitty/vendor/datatables/buttons.server-side.js"></script>
<script type="text/javascript">$(function(){window.LaravelDataTables=window.LaravelDataTables||{};window.LaravelDataTables["partners-table"]=$("#partners-table").DataTable({"serverSide":true,"processing":true,"ajax":{"url":"http:\/\/kitty\/admin\/partners","type":"GET","data":function(data) {
for (var i = 0, len = data.columns.length; i < len; i++) {
if (!data.columns[i].search.value) delete data.columns[i].search;
if (data.columns[i].searchable === true) delete data.columns[i].searchable;
if (data.columns[i].orderable === true) delete data.columns[i].orderable;
if (data.columns[i].data === data.columns[i].name) delete data.columns[i].name;
}
delete data.search.regex;}},"columns":[{"data":"id","name":"id","title":"Id","orderable":true,"searchable":true},{"data":"title","name":"title","title":"Title","orderable":true,"searchable":true}],"dom":"Bfrtip","order":[[1,"desc"]],"buttons":[{"extend":"create"},{"extend":"export"},{"extend":"print"},{"extend":"reset"},{"extend":"reload"}]});});
</script>
the reason why your data isn't displaying on the table is because of this line of code:
->buttons(
Button::make('create'),
Button::make('export'),
Button::make('print'),
Button::make('reset'),
Button::make('reload')
);
comment this line of code and the data will be displayed properly.
Whenever I try to add a product to a wishlist I am redirected to a login page where I enter my credentials and after that it keeps reloading and this error appears.
Thereafter, when I return to home page and refresh I am logged in. But when I try to access a page directly which requires login, it works perfectly fine. This error has been appearing for sometime now, it was previously working fine.
routes:
Auth::routes();
Route::group(['middleware'=>'auth'],function (){
Route::get('/checkout','PageController#checkout')->name('checkout');
Route::post('/coupon','PageController#coupon')->name('coupon.check');
Route::post('/order', 'OrderController#store')->name('order.store');
Route::post('/orderinfo', 'OrderInfoController#store')->name('orderinfo.store');
Route::get('/invoice/{order}','PageController#invoice')->name('invoice');
Route::resource('/profile', 'ProfileController');
Route::get('/wishlist', 'WishlistController#index')->name('wishlist.index');
Route::get('/wishlist/{product_id}/remove', 'WishlistController#remove')->name('wishlist.remove');
Route::get('/wishlist/{product_id}', 'WishlistController#quick')->name('wishlist.quick');
Route::resource('/review', 'ReviewController');
Route::get('/orders', 'PageController#order')->name('orders');
Route::group(['middleware'=>'admin'],function () {
Route::resource('/admin/products', 'ProductController');
Route::resource('/admin/categories', 'CategoryController');
Route::resource('/admin/subcategories', 'SubcategoryController');
Route::resource('/admin/coupons', 'CouponController');
Route::resource('/admin/taxes', 'TaxController');
Route::resource('/admin/discounts', 'DiscountController');
Route::get('/admin/index', 'PageController#admin')->name('admin.index');
Route::post('/admin/ajax/category', 'PageController#ajax')->name('ajax.category');
Route::resource('/admin/users', 'UserController');
Route::resource('/admin/tracks', 'TrackController');
Route::get('/order', 'OrderController#index')->name('order.index');
Route::get('/order/{order}', 'OrderController#show')->name('order.show');
});
});
Route::get('/product/{product}','PageController#product')->name('product.view');
Route::get('/','PageController#index')->name('index');
Route::get('/about-us','PageController#about_us')->name('about_us');
Route::resource('/contact-us','ContactController');
Route::get('/shop','PageController#shop')->name('shop');
Route::get('/home', 'HomeController#index')->name('home');
Route::post('/cart', 'CartController#add')->name('cart.add');
Route::get('/cart{product}', 'CartController#quick')->name('cart.quick');
Route::get('/cart/show', 'CartController#show')->name('cart.show');
Route::patch('/cart/{product_id}', 'CartController#update')->name('cart.update');
Route::get('/cart/{product}/remove', 'CartController#remove')->name('cart.remove');
Route::get('/shop/filter/{subcategory_id}','PageController#filter')->name('filter.product');
Route::get('/shop/category/{category}','PageController#shop_2')->name('filter.categories');
Login Controller:
<?php
namespace App\Http\Controllers\Auth;
use App\Category;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function redirectTo()
{
}
public function showLoginForm()
{
$categories = Category::all();
$cart_items = session()->get('cart');
$sub_total = 0;
if (!empty($cart_items)) {
foreach ($cart_items as $item) {
$sub_total = ($item['price'] * $item['quantity']) + $sub_total;
}
}
return view('login', ['cart_items' => $cart_items, 'sub_total' => $sub_total,'categories'=>$categories]);
}
}
This is how I am sending get request and which gives error after login:
<a class="add-wishlist" title="wishlist" href="{{route('wishlist.quick',$product->id)}}"><i class="fa fa-heart"></i></a>
Wishlist Controller:
<?php
namespace App\Http\Controllers;
use App\Category;
use App\Helpers\helper;
use App\Product;
use App\Wishlist;
use Illuminate\Http\Request;
class WishlistController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$categories= Category::all();
$cart_items = helper::cart_data();
$sub_total = helper::sub_total($cart_items);
$user_id = auth()->user()->id;
$wishlist = Wishlist::all()->where('user_id', '=', $user_id);
$products = [];
foreach ($wishlist as $list) {
$products[] = Product::find($list->product_id);
}
return view('wishlist', ['wishlist' => $wishlist, 'products' => $products,'sub_total'=>$sub_total,'categories'=>$categories,'cart_items'=>$cart_items]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
$user_id = auth()->user()->id;
$check = Wishlist::all()->where('user_id', $user_id)->where('product_id', $request['product_id']);
if ($check->isEmpty()) {
Wishlist::create([
'user_id' => $user_id,
'product_id' => $request['product_id']
]);
}
return redirect()->back();
}
/**
* Display the specified resource.
*
* #param \App\Wishlist $wishlist
* #return \Illuminate\Http\Response
*/
public function show(Wishlist $wishlist)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Wishlist $wishlist
* #return \Illuminate\Http\Response
*/
public function edit(Wishlist $wishlist)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Wishlist $wishlist
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Wishlist $wishlist)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\Wishlist $wishlist
* #return \Illuminate\Http\Response
*/
public function remove(Request $request)
{
//
$user_id = auth()->user()->id;
Wishlist::where('user_id', $user_id)->where('product_id', $request['product_id'])->delete();
return redirect()->back();
}
public function quick($product_id)
{
//
$user_id = auth()->user()->id;
$check = Wishlist::all()->where('user_id', $user_id)->where('product_id', $product_id);
if ($check->isEmpty()) {
Wishlist::create([
'user_id' => $user_id,
'product_id' => $product_id
]);
}
return redirect()->back();
}
}
Firstly, 419 error indicate an expired session. I notice you are using the session helper method session() inside showLoginForm(). You should be aware that if a user is logged out or his/her session expires then that user cannot access the data stored in that session as it will be wiped clean. Trying to access session data this way through showLoginForm is counter-intuitive as the user will most likely have been logged out or had an expired session before accessing the login form - except for the case where the user is accessing the login form for the first time. This could be a possible cause of the 419 errors.
You can remove the piece of code where you are trying to access the session data to any of your several controllers that require authentication. Then, you are sure that the user has a valid session before accessing session data.
However, to redirect users after a successful login Laravel uses either the $redirectTo variable or redirectTo() method of the LoginController. If the method is defined, it overrides the variable and if not, the variable is used.
From your LoginController, none of them is defined. Usually, the variable is set to redirect to the homepage - $redirectTo = '/home'. However, to meet your requirement of redirecting to the page that required the login, you must use the redirectTo() method.
You can achieve this by using the helper method url()->previous() within LoginController.php like this:
public static $previous;
public function showLoginForm() {
self::$previous = url()->previous();
// continue with your code.
}
public function redirectTo()
{
return self::$previous;
}
notice that I store the previous url when i first show the login form. after a successful login, this url should be available for me to redirect to.
UPDATE 1:
The problem route
Route::get('/cart{product}', 'CartController#quick')->name('cart.quick');
has a problem. You are missing a forward slash after /cart. You should notice this issue when you look at the generated url in the link. The correct form should be
Route::get('/cart/{product}', 'CartController#quick')->name('cart.quick');
UPDATE 2:
Since the route wishlist.quick is going through the auth middleware, do not use redirect()->back() for going back to the same page after user action with that route.
This is because, with the auth middleware in place, redirect()->back() is not always pointing to same location.
For instance, an unauthenticated user accessing the wishlist.quick route will be redirected to the login page. If login is successful the request continues to wishlist.quick route. Now, try to guess where the redirect()->back() inside WishlistController#quick is pointing to. Right! Surprisingly, it is pointing to the login page. So now the authenticated user completes his/her request with WishlistController#quick and is directed to the login page again. The login controller detects the user is authenticated and redirects the user to wherever he/she is coming from - WishlistController#quick. Again, there is redirect()->back() sending the user back again to the login page. You see the infinite redirect loop clearly in this funny scenario.
SOLUTION:
Change the line
return redirect()->back();
to
return $this->index();
Since WishlistController#quick doesn't return a view of its own, WishlistController#index is the best place to return to. Infact, you have to make this change for all routes that pass through a middleware and redirects the user back.
In other words, do not use redirect()->back() in a route that goes through middleware, if you really mean to go back to the same page.
A common issue with Laravel throwing a 419 error is because of a missing #csrf inside the form.
<form method="post" action="<some route>" >
#csrf
<input ...... />
</form>
If you are sending any data in a form, please ensure you have the above CSRF token.
If you do have this token, can you add the form in the main question?
I can't open open 2 forms (create, edit) that are validated by the same form request class.
When I click on the create or edit button, I just get a redirect to the same page with 302 Found status code visible in Dev Tools, without form being open.
When I remove form request validation from the methods in a controller, I can open forms normally.
Controller:
...
use App\Http\Requests\AreaRequest;
...
public function edit(Area $area,AreaRequest $request) //it works if I remove AreaRequest $request
{
return view('backend.areas.edit', compact('area'));
}
public function create(AreaRequest $request)
{
return view('backend.areas.create');
}
Request:
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class AreaRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|string'
];
}
}
Dev tools image:
You are using the form request in wrong method
edit and create are for showing the form view
the validation should goes to store or update
public function store(AreaRequest $request)
{
}
public function update(AreaRequest $request, Area $area)
{
}
I am learning laravel following a tutorial. I am stuck with this error
ErrorException in Macroable.php line 81:
Method open does not exist. (View: path\to\project\resources\views\form.blade.php)
I am using FormFacade. earlier I was facing an error saying:
Call to undefined method Illuminate\Foundation\Application::bindShared()
which I overcame by replacing bindShared with singleton all over the file
/path/project/vendor/illuminate/html/HtmlServiceProvider.php
form.blade.php
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
<h1>Create a new form</h1>
<hr/>
{{ Form::open() }}
{{ Form::close() }}
</body>
</html>
HtmlServiceProvider.php
use Illuminate\Support\ServiceProvider;
class HtmlServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* #var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* #return void
*/
public function register()
{
$this->registerHtmlBuilder();
$this->registerFormBuilder();
$this->app->alias('html', 'Illuminate\Html\HtmlBuilder');
$this->app->alias('form', 'Illuminate\Html\FormBuilder');
}
/**
* Register the HTML builder instance.
*
* #return void
*/
protected function registerHtmlBuilder()
{
$this->app->singleton('html', function($app)
{
return new HtmlBuilder($app['url']);
});
}
/**
* Register the form builder instance.
*
* #return void
*/
protected function registerFormBuilder()
{
$this->app->singleton('form', function($app)
{
$form = new FormBuilder($app['html'], $app['url'], $app['session.store']->getToken());
return $form->setSessionStore($app['session.store']);
});
}
/**
* Get the services provided by the provider.
*
* #return array
*/
public function provides()
{
return array('html', 'form');
}
}
Plese Help.
illuminate/html was deprecated for Laravel 5.0, and has not been updated to work with Laravel 5.1+.
You need to replace it with the laravelcollective/html package.
Add in your config/app.php provider:
Collective\Html\HtmlServiceProvider::class,
and add alias:
'Html' => Collective\Html\HtmlFacade::class,
and replace form open and close :
{!! Form::open() !!}
{!! Form::close() !!}
notes:
This is for laravel 5.