I am trying to pass the ID value from the blade file into ajax so it the data table will be routed and will call the ProductActivities function in ProductController.
Here's my snippet code for show() function in ProductController:
public function show($id)
{
$product = Product::find($id);
$data = Product::with(['user_modify'], 'id', $product->user_modified)
->where('product_id', '=', $id)->first();
$category = Category::select('category_name')
->where('category_id', '=', $data->product_type)
->pluck('category_name')
->first();
if($data->count() > 0){
return view('product.view', compact('data', 'category'));
}else{
Toastr::error('Product cannot be retrieved.', 'Error');
return view('product.index');
}
}
And here's the snippet code of JavaScript for the DataTable initialization in view.blade.php file:
#push('js')
<script>
$(function () {
$("#prod_log_tbl").DataTable({
responsive:true,
stateSave:false,
scrollY:true,
autoWidth: false,
ajax: {{ url('product/activities', [Request::segment(3)]) }},
order:[0, 'desc'],
searchable: false,
sortable:false,
fixedColumns: true
});
});
</script>
#endpush
line of code for route in web.php:
Route::get('product/activities/{id}', 'Master\ProductController#ProductActivities')->name('product/activities/{id}');
snippet code for the ProductActivities() function in ProductController:
public function ProductActivities($id)
{
$dataAct = Activity::all()->where('subject_id', '=', $id);
return Datatables::of($dataAct)->make(true);
}
And here's the result of my current progress:
In the screenshot of result the URL that ajax shows has additional values after the ID which I think causes of the DataTable error.
I don't know How I am getting this error? How can I implement the passing of ID from the view blade file through DataTable ajax into the ProductController?
P.S. I use Yajra/DataTable package for Laravel.
I think you do not need php echo in you Ajax url, route helper syntax is
{{ route('routeName', ['id' => 1]) }}
you need route name and parameter, another way is using url helper
{{ url('product/activities/', [Request::segment(3)]) }}
Beside this if you want to use model refer documentation, using first() will give you only one object, you need a collection, better considering get().
Related
i want to show the total of amount in the home view blade
(table = payments , colon = amount)
i tested another method by route , this it work fine but the result show in /test of course:
Route::get('/test', function(){
$total = DB::table('payments')
->where('status', '=', 'success') //this for collect only the success payments
->sum('payments.amount');
return $total; // work fine the result is correct
});
but my purpose is to display this result inside the home view
by move the function from the previous code from route to controller and call it in the view
for the controller i have Homecontroller but the function index is aleardy used , so i create new function in this controller i try this
public function show(){
$total = DB::table('payments')
->where('status', '=', 'success')
->sum('payments.amount');
return view('home' , $total);
}
for routing i put this
Route::get('/home', 'HomeController#show');
i try this inside the view but didnt work :
<h1>{{$total}}</h1>
You can use with()
public function show(){
$total = DB::table('payments')->where('status', '=', 'success')
->sum('payments.amount');
return view('home')->with('total', $total);
}
according to documentation :
The second argument is an "array" of data that should be made available to the view.
try :
return view('home' , ['total' => $total]);
or use ->with('key',$value) :
return view('home')->with('total', $total);
you can also use compact() function, it is an inbuilt function in PHP and used to create an array using variables:
return view('home' , compact("total"));
You can send total variable result with compact function to view like
below.
return view('home' , compact('total'));
// You can call it in home.blade like this
//for example
#if(isset($total ))
<li>{{ $total }}</li>
#endif
I can't get the data from the database. Getting an error:
ErrorException (E_ERROR)
Undefined variable: user
(View:/Users/alex/Desktop/sites/tj/resources/views/user/submissions.blade.php)
Controller:
public function __construct()
{
$this->middleware('auth', ['except' => ['getById',
'getByUsername', 'submissions', 'comments', 'showSubmissions',
'showComments']]);
}
and
public function showSubmissions($username)
{
$user = new UserResource(
User::withTrashed()->where('username', $username)->firstOrFail(),
true
);
$submissions = SubmissionResource::collection(
Submission::whereUserId($user->id)
->withTrashed()
->orderBy('created_at', 'desc')
->simplePaginate(15)
);
return view('user.submissions', compact('user', 'submissions'));
}
View:
{{ $user->username }}
API:
Route::get('/user', 'UserController#getByUsername');
I need get information about user (username).
What is the problem and where is the error?
Based on your comment you have this route:
Route::get('/submission', function () {
return view('user.submissions');
});
When you are loading this view, you are not passing the user object to it. Then when the view is running, it is trying to access a variable that does not exist.
To fix this, you need to pass a variable to the view you are loading. For example, you could do something like this:
Route::get('/submission', function () {
return view('user.submissions', ['user' => auth()->user()]);
});
Note that you can change how you get the user instance depending on your use case. I am just getting the authenticated user to demonstrate the principle.
I have modified default auth method in controller which redirects user after custom login to set_password page. The problem is I can redirect it well to the desired page but I need to simultaneously pass two dynamic variables which are returned through querying database, which I am unable to pass with redirect.
My modified controller method is as follows:-
protected function authenticated(Request $request, $user)
{
$activated_up = User::where('id_user',Auth::user()->id_user)
->where(function($query) {
$query->where('activated_up', '=', '1')
->orWhere('activated_up', '=','0');
})
->get(['activated_up']);
$showuser = UserProfile::where('id_user',Auth::user()->id_user)->first();
return redirect()->route('set_password',['activated_up' => $activated_up, 'showuser' => $showuser]);
}
I know that to pass a variable to an view, I need to use the compact method like follows:-
return view('set_password', compact('activated_up', 'showuser'); but it cant be done with redirect.
The way I have redirected means I am passing parameters to route in the controller method, but I need to pass variables to the redirected view instead of parameters. How to achieve that?
protected function authenticated(Request $request, $user)
{
$activated_up = User::where('id_user',Auth::user()->id_user)
->where(function($query) {
$query->where('activated_up', '=', '1')
->orWhere('activated_up', '=','0');
})
->get(['activated_up']);
$showuser = UserProfile::where('id_user',Auth::user()->id_user)->first();
return redirect()->route('set_password',['activated_up' => $activated_up, 'showuser' => $showuser]);
}
you can use With
return redirect()->route('set_password')->with('data', ['some kind of
data']);
in your view
#if (session::has('data'))
The data is {{ session::get('data') }}
#endif
Tried as described in the answer by Kuldeep Mishra but could not achieve it though, anyways I found a workaround to achieve my desired output. What I did is changed my authenticated method to this:-
protected function authenticated(Request $request, $user)
{
return redirect()->route('set_password');
}
I only redirected to the set_password route from the above method and made new method in the controller to show the view with the compacted variables like this:-
public function setPasswordForm(Request $request)
{
$activated_up = User::where('id_user',Auth::user()->id_user)
->where(function($query) {
$query->where('activated_up', '=', '1')
->orWhere('activated_up', '=','0');
})
->get(['activated_up']);
$showuser = UserProfile::where('id_user',Auth::user()->id_user)->first();
return view('set_password', compact('activated_up', 'showuser'));
}
And a small change in route web.php file:-
Route::get('/set_password', 'Controller#setPasswordForm')->name('set_password');
So finally I was able to redirect to desired page with the desired view loaded with dynamic variables.
I'm using laravel 5.4 and the latest version of yajra/laravel-datatables as a service.
I have it working fine with one datatable on a page. I want to create a dashboard of unrelated tables. Users, products, bookings etc.
I was hoping to have my controller look something like this:
public function index(ProductsDataTable $productDatatable, UsersDataTable $userDatatable)
{
$user = Auth::user();
$products = $user->products;
return view('admin.dashboard', compact('products', 'user', 'productDatatable', 'userDatatable'));
}
and in my blade do
#section('content')
{!! $productDatatable->table() !!}
{!! $userDatatable->table() !!}
#endsection
#push('scripts')
{!! $dataTable->scripts() !!}
#endpush
However this obviously doesn't work. I'm unsure how to proceed.
I tried to create a route for each datatable but wasn't sure how to reference it from my dashboard controller.
I'm sure there's a better way of implementing multiple tables in one view, but this is what I came up with after reviewing this. Comments/improvements would be highly appreciated.
Controller
The controller will render the tables once in the index() method but will fetch data from both the getUsers() method or getProducts() method.
// DashboardController.php
public function index(UsersDataTable $usersDataTable, ProductsDataTable $productsDataTable)
{
return view('dashboard.index', [
'usersDataTable' => $usersDataTable->html(),
'productsDataTable' => $productsDataTable->html()
]);
}
//Gets Users JSON
public function getUsers(UsersDataTable $usersDataTable)
{
return $usersDataTable->render('admin.dashboard');
}
//Gets Products JSON
public function getProducts(ProductsDataTable $productsDataTable)
{
return $productsDataTable->render('admin.dashboard');
}
Routes
Add two extra routes that will be used to fetch Users and Projects data.
// web.php
Route::get('/', 'DashboardController#index')->name('dashboard.index');
Route::get('projects', 'DashboardController#getProjects')->name('dashboard.projects');
Route::get('users', 'DashboardController#getUsers')->name('dashboard.users');
DataTables Service Class
For both the UsersDataTable and ProductsDataTable service classes, include the relevant routes we created above.
// UsersDataTable.php
public function html()
{
return $this->builder()
->minifiedAjax( route('dashboard.users') );
}
View
// dashboard.blade.php
#section('content')
{!! $productsDataTable->table() !!}
{!! $usersDataTable->table() !!}
#endsection
#push('scripts')
{!! $productsDataTable->scripts() !!}
{!! $usersDataTable->scripts() !!}
#endpush
Submitted a question to the creator of the package. This is his response:
Unfortunately, DataTable service class is designed to handle single instance. However, I think we can make a workaround for it by adding additional query param in our request for us to identify which class is being requested to handle the request.
Maybe something like below:
public function index(ProductsDataTable $productDatatable, UsersDataTable $userDatatable)
{
if (request()->has('product') {
return $productDatatable->render('view');
}
if (request()->has('user') {
return $productDatatable->render('view');
}
$user = Auth::user();
$products = $user->products;
return view('admin.dashboard', compact('products', 'user', 'productDatatable', 'userDatatable'));
}
Step 1:
Define a route '/home-page' in web.php/route.php' (depending on the laravel version you are using) that returns the view called 'dt.blade.php'. (we will create this view in step 4)
i.e. Route::get('/home-page', function(){
return view('dt');
});
Step 2:
Suppose you want to display two dataTables in 'dt.blade.php' view. (first datatable shows all the students in a school while other shows all the classes in a school)
To do that, you need to create two Builder instances ('Builder' class belongs to DataTables package) in the '/home-page' route's callback function and pass them to the 'dt.blade.php' view . i.e
Route::get('/home-page', function() {
$student_dt = app(Builder::class)->columns(['id', 'student_name'])->ajax('/show-students-datatable')->setTableId('t1');
$classes_dt = app(Builder::class)->columns(['id', 'class_name'])->ajax('show-classes-datatable')->setTableId('t2');
return view('dt', compact('student_dt', 'classes_dt'));
});
Step 3
Now define two more routes in web.php/route.php file:
Route::get('/show-students-datatable', function () {
return datatables(App\Student::query()->select(['id', 'student_name']))->toJson();
});
Route::get('/show-classes-datatable', function () {
return datatables(App\Class::query()->select(['id', 'class_name'])))->toJson();
});
Step 4
Define the 'db.blade.php' view, this view show both the dataTables that were passed to it in step 1.
#extends('layouts.master')
#section('content')
{{ $student_dt->table() }}
{{ $classes_dt->table() }}
#endsection
#push('scripts')
{{$student_dt->scripts()}}
{{$classes_dt->scripts()}}
#endpush
I have a function where:
After I click the link named "hapus", the related data will be deleted and I want to have a popup alert to show that the data has been deleted.
*sorry for my bad english
*hapus technically means destroy
this the code:
public function hapus(Request $request, $id)
{
DB::table('kelompok')
->where('id', $id)
->delete();
return redirect()->back();
}
Use with() in your controller
function hapus(Request $request, $id)
{
DB::table('kelompok')
->where('id', $id)
->delete();
return redirect()->back()->with('alert', 'Deleted!');
}
In your blade template, retrieve the session after being redirected from controller:
#if (session('alert'))
<div class="alert alert-success">
{{ session('alert') }}
</div>
#endif
Extending #pbwned's answer,
you can also use javascript alert box in your blade view to display the flash session/message.
For example:
<script>
var msg = '{{Session::get('alert')}}';
var exist = '{{Session::has('alert')}}';
if(exist){
alert(msg);
}
</script>
Hope it helps =)