Undefined variable problem on Laravel 9.x - php

I'm trying to get a my title variable from my control page and display it on the about page.
I don't think I have a typo, but it might me. I'm not sure.
Here is my control page code;
class PagesController extends Controller
{
public function index(){
$title = 'Welcome to Laravel';
return view ('pages.index')->with('title', $title);
}
public function about(){
$title = 'About us';
return view ('pages.about')->with('title', $title);
}
public function services(){
$title = 'The services';
return view ('pages.services')->with('title', $title);
}
}
In this page, the index and services functions work fine, but I can't get the about page.
Here is my display pages;
This is Index page
#extends('layouts.app')
#section('content')
<h1>{{$title}}</h1>
<p>This is the Laravel Application</p>
#endsection
This is the about page:
#extends('layouts.app')
#section('content')
<h1>{{$title}}</h1>
<p>This is the About page</p>
#endsection
The error I have

Do this:
return view ('pages.index', compact('title'));
or:
return view ('pages.index', [
'title' => $title
]);

Since you are returning just the title, there isn't any need to call any verbs. Rather you should directly call the view:
route::view('/about', 'Pagecontroller#about');
or
pass the parameter by compact:
return view ('pages.index', compact('title'));
or
return view ('pages.index', ['title' => $title]);

Since this is a test application from a lesson, I forgot to delete some extra code in my route file.
This is my route file:
Route::get('/', 'App\Http\Controllers\PagesController#index');
Route::get('/about', 'App\Http\Controllers\PagesController#about');
Route::get('/services', 'App\Http\Controllers\PagesController#services');
The commented area shouldn't be here. That was the whole problem over here...
// Route::get('/about', function(){
// return view ('pages.about');
// });

This form of passing variables is a short-lived entry of a variable into the session. Then accessing the variable on the page should look like this:
{{ session('title') }}
If you want to pass data to the view, then you need to use the method
return view('pages.services', ['title' => $title]);
Laravel views

Related

Laravel Undefined variable: intent Facade\Ignition\Exceptions\ViewException

I tried looking for all the possible solutions none of it worked and this is very basic trying to send data from a controller to view in Laravel.
Paymentcontroller
public function payment() {
$plans =[
'Basic' => "Monthly"
];
$intent = $user->createSetupIntent();
return view('pages.subscription', compact('intent', 'plans'));
}
PageController
public function index(string $page)
{
if (view()->exists("pages.{$page}")) {
return view("pages.{$page}");
}
return abort(404);
}
View pages.subscription
<div>
{{ $intent }}
</div>
route
Route::get('{page}', ['as' => 'page.index', 'uses' => 'PageController#index']);
Route::get('/subscription', 'PaymentController#payment');
This makes the page work but doesn't display the data
Move Route::get('/subscription', 'PaymentController#payment'); before Route::get('{page}',.... (it should be your last route in the list).
Currently when you call /subscription endpoint you are calling PageController#index, but it doesn't contain logic of your PaymentController#payment and doesn't pass any data to view.

Laravel Datatables - Multiple tables on one view

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

New route or another way to call a function from controller with ajax? Laravel 5.2 , Ajax

Is it possible to call a function in the controller without using a route or should I make a new route with two parameters as below that redirects to the specific page after the session has been added?
route::get('addsesion/{session-name}/{session slug};
If it's possible with ajax, can someone please point me in the right direction?
Basically what I would like to do is call the function addSession($session_name, $slug) from a controller with ajax on link <a href/> click , where it stores my specific session name and current page's slug.
It should call this addSession function on a click, store session data and then redirect to a different url. e.g. /seeparts, where it displays all saved session data.
Do I have to make a new route route::get('addsesion/{param1 - session-name}/{param2 - session slug}', currentController#addSession ); and then use that route as an ajax url? Or is there any other way how to use the controller's function?
My current Controller:
public function showAll() {
$parts = \DB::table() - > all();
$data = [
'parts' => $parts,
];
return view('partlist', $data);
}
public function showCpu($slug) {
// Specification query
$specs = \DB::table() - > select($select_columns) - > where('slug', $slug) - > first();
$data = [
'specs' => $specs,
'slug' => $slug
];
return view('part', $data);
}
//Add session - call this function
public function addSession($session_name, $slug) {\
Session::put($session_name, $slug);
}
}
part.blade.php:
<html>
#include('head.blade.php')
</body>
//on .add-to-partlist click adds session name that is specified in html and the current slug of the page
<a class="add-to-partlist" href="/seeparts" >Add to partlist</a>
</body>
</html>
I think you can use Service Injection binding controller function in your view.
Maybe you can reference it, https://laravel.com/docs/master/blade#service-injection.
For example:
<html>
#include('head.blade.php')
#inject('currentController', 'App\Http\Controllers\currentController')
</body>
//on .add-to-partlist click adds session name that is specified in html and the current slug of the page
<a class="add-to-partlist" href="/seeparts" onClick="{{ $currentController->addSession($session_name, $slug) }}">HERE</a>
</body>
</html>

pass auth::user as data variable with route

I want that when the user click the profile page i want to pass Auth::user()->username as argument to my userController's show method.I have the profile link as following:
<li>Profile</li>
And in my route i have the following route
Route::get('/profile/{username}',function(){
return View::make('user.show')->with($username);
});
my question is how i can set username in my '/profile/{username}' as Auth::user()->username when i click the profile link?currently the profile link does not attach any parameter with it
First of all
{{URL::to('/profile')}} is not pointing to Route::get('/profile/{username}) url,there are two different routes
So what you need to do is either change the link , i.e.
{{URL::to('/profile/' . \Auth::user()->username)}}
and then in your route file
Route::get('/profile/{username}',function($username){
return View::make('user.show')->with(['username' => $username]);
});
//note that you need to pass the array in with() method
or you can do this
Route::get('/profile/{username}',function($username){
return View::make('user.show',compact('username'));
});
When the user clicks on profile link:
<li>
My Profile
</li>
The UserController#show method is called.
<?php
// routes.php
Route::get('profile/{username}', 'UserController#show')->name('user.show');
// UserController.php
public function show($username)
{
$user = User::whereUsername($username)->first();
return view('user.show', compact('user'));
}
and a View response is returned to the user.
#update
If you need is just redirect the control to the UserController#show method, you can do this:
<li>
My Profile
</li>
<?php
// routes.php
Route::get('profile/{username}', function ($username) {
return redirect()->route('user.show', Auth::id());
})->name('user.profile');
Now if you want customize the UserController#show action:
<li>
My Profile
</li>
The UserController#show method is called.
<?php
// routes.php
Route::resource('user', 'UserController', ['except' => ['show']);
Route::get('profile/{username}', 'UserController#profile')->name('user.profile');
Now you can delete the UserController#show method if you want or change the profile method name to show.
// UserController.php
public function profile($username)
{
$user = User::whereUsername($username)->first();
return view('user.show', compact('user'));
}
A quick way is to setup a redirect from /profile and it won't break the functionality if they want to view someone else's profile.
Route::get('/profile',function(){
return Redirect::to('/profile/'.Auth::user()->username);
}
However, I'd recommend doing an Auth::check() before the redirect.
i did something like the following
<li>Profile</li>
and in route.php:
Route::get('/profile',function(){
return redirect()->route('user.show',[Auth::user()->username]);
});

Laravel: Undefined variable content

I have setup a Route:
Route::resource('conferences', 'ConferencesController)
Artisan therefore shows me a route:
POST conferences | conferences.store | ConferencesController#store
When I submit a Form from the create View, I get the error that a variable in my layout file has not been defined.
Undefined variable: content is shown, nothing has been posted.
I opened my form like this:
{{ Form::open(array('url' => '/conferences', 'class' => 'conference-form')) }}
And finally, my store method in ConferencesController looks like this:
public function store()
{
$validator = Validator::make(Input::all(), Conference::$rules);
if($validator->passes()){
$conference = new Conference();
$conference->title = Input::get('title');
$conference->description = Input::get('description');
$conference->location = Input::get('location');
$conference->plannedTime = Input::get('plannedTime');
$conference->save();
Mail::pretend();
Mail::send('emails.conference.create', ['title' => Input::get('title'), 'location' => Input::get('location'), 'plannedTime' => Input::get('plannedTime')], function($message){
$message->to('email')->subject('Een nieuw evenement is gemaakt.');
});
Redirect::to('/conferences')->with('message', 'Nieuw event is aangemaakt!');
} else {
Redirect::to('/')->with('message', 'Iets ging mis');
}
}
How do I fix this error?
** EDIT: Added create method **
public function create(){
$this->layout->content = View::make('conferences.create');
}
This should be really straight forward. In your views directory we usually have a folder called layouts where we put the page structure something like:
// default.blade.php
<html>
<head> </head>
<body>
#yield('content'); // this is where your views will be loaded
</body>
</html>
then in your case you should create a conferences folder and then a file create.blade.php in it.
#extends('layouts.default')
#section('content')
// your forms etc
#stop
And in your create method inside ConferencesController
public function create() {
return View::make('conferences.create');
}
And one last thing, when you try to send the email you should be passing an email address inside the to() function and you are passing a string

Categories