Undefined variable in laravel 9 - php

I'm creating a user registration form. I create a form in the Component. when the user registers he redirects to the user page where he sees all users. when he wanted to edit or update something from in his details he redirects to the same registration form page but this will be a new URL and new Title. I'm getting an undefined variable $title and $url error. when I pass data from the controller to view I get this error.
Registration Form Controller
public function create(Request $request)
{
$url = url('/register');
$title = ("Registration Form");
$data = compact( 'url');
return view('RegistrationForm')->with($data);
}
public function store (Request $request)
{
$request->validate(
[
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required|email',
'password' => 'required',
'confirm_password' => 'required|same:password|min:8',
'address' => 'required',
'country' => 'required',
'state' => 'required',
'city' => 'required',
'gender' => 'required',
'tearms_and_conditions' => 'required',
],
[
'firstname.required' => 'Please enter your First Name',
'lastname.required' => 'Please nter your Last Name',
'email.required' => 'Please enter an Email',
'password.required' => 'Please Enter a Password'
],
);
$users = new Users;
$users->firstname = $request['firstname'];
$users->lastname = $request['lastname'];
$users->email = $request['email'];
$users->password = md5($request['password']);
$users->address = $request['address'];
$users->country = $request['country'];
$users->state = $request['state'];
$users->city = $request['city'];
$users->gender = $request['gender'];
$users->date_of_birth = $request['date_of_birth'];
$users->save();
return redirect('/register/view');
}
public function view (Request $request)
{
$users = Users::all();
$data = compact('users');
return view('user-view')->with($data);
}
public function delete($id)
{
$user = Users::find($id);
echo "<pre>";
print_r ($user);
die;
return redirect('/register/view');
}
public function edit($id)
{
$user = Users::find($id);
if (is_null($user))
{
return redirect('/register/view');
}
else
{
$url = url("user/update"."/". $id);
$title = "Update Details";
$data = compact('user', 'url', 'title');
return redirect('/register')->with($data);
}
}
public function update($id, Request $request)
{
$user = Users::find($id);
$users->firstname = $request['firstname'];
$users->lastname = $request['lastname'];
$users->email = $request['email'];
$users->address = $request['address'];
$users->country = $request['country'];
$users->state = $request['state'];
$users->city = $request['city'];
$users->gender = $request['gender'];
$users->date_of_birth = $request['date_of_birth'];
$users->save();
return redirect('register/view');
}
}
Route
Route::get('/register', [RegistrationFormController::class, 'index']);
View
<body>
<h1> {{$title}} </h1>
<x-registration-form-component :country="$country" :url="$url" />
RegisreationFormComponent

You have to pass the $data variable as the second argument of the view() method:
public function index ()
{
$url = url('/register');
$title = "Registration Form";
$data = compact('title', 'url');
return view('RegistrationForm', $data);
}

First, to answer your question:
When you use the compact method, you are placing those values in an array. You would need to call them like so:
{{ $data['title'] }}
{{ $data['url'] }}
However, you could clean the code up a little bit like this:
public function index()
{
return view('RegistrationForm', [
'url' => url('/register'),
'title' => 'Registration Form',
]);
}
You can then use them in the blade file like so:
{{ $url }}
{{ $title }}

Related

generating dynamic pdf with DOMPDF in laravel

I am trying to generate an invoice pdf with dynamic data (mostly taken from a form). This is the code:
class PDFController extends Controller
{
public function invoice() {
$institution = $this->institution();
$user = $this->user();
$invoice = $this->invoice_form();
return view('pdf-generation.invoice')->with(['institution' => $institution, 'user' => $user]);
}
public function institution() {
$institution = Institution::where('id', 1)->get()->first();
return $institution;
}
public function user() {
$user = Auth::user();
return $user;
}
public function invoice_form(Request $request) {
$this->validate($request, array(
'furnizor-select' => 'required',
'document-number' => 'required',
'document-date' => 'required',
'due-date' => 'required',
'discount-procent' => 'required',
'discount-value' => 'required',
'total-value' => 'required',
'nir-number' => 'nullable'
));
$invoice = new \App\Models\Invoice();
$invoice->provider_id = $request->input('furnizor-select');
$invoice->number = $request->input('document-number');
$invoice->document_date = $request->input('document-date');
$invoice->due_date = $request->input('due-date');
$invoice->discount_procent = $request->input('discount-procent');
$invoice->discount_value = $request->input('discount-value');
$invoice->total = $request->input('total-value');
$invoice->save();
$invoices = Invoice::all();
$invoice_id = $invoices->last()->id;
$old_date = $request->input('document-date');
$new_date = date("d-m-Y", strtotime($old_date));
$provider_id = $request->input('furnizor-select');
$provider = Provider::where('id', $provider_id)->get();
$invoice_number = $request->input('document-number');
$old_due_date = $request->input('due-date');
$new_due_date = date("d-m-Y", strtotime($old_due_date));
$filename = 'pdfs/nir'.$invoice_id.'.pdf';
}
}
However, I am getting this error:
Too few arguments to function App\Http\Controllers\PDFController::invoice_form(), 0 passed in /Users/cristimamota/NEWSAJ BACKUP PRE FINAL/app/Http/Controllers/PDFController.php on line 17 and exactly 1 expected
And this is because in the invoice() function, I am calling the invoice_form() function and is getting no parameter.. I think this is not the correct way to do it. How should I approach it?
Since your invoice_form(Request $request) requires a Request model as parameter you can change your invoice() method to take $request as parameter and pass that $request to your invoice_form() method. Change
public function invoice() {
$institution = $this->institution();
$user = $this->user();
$invoice = $this->invoice_form();
return view('pdf-generation.invoice')->with(['institution' => $institution, 'user' => $user]);
}
to
public function invoice(Request $request) {
$institution = $this->institution();
$user = $this->user();
$invoice = $this->invoice_form($request);
return view('pdf-generation.invoice')->with([
'institution' => $institution,
'user' => $user
]);
}

CodeIgniter 4 redirect()->to() not working on IE

I am getting error from IE when I redirect to "dashboard" controller after settings session values in "login" function ( return redirect()->to(base_url('dashboard'));). I have this working on Chrome, Firefox, Edge, and Opera.
I am using public $sessionDriver = 'CodeIgniter\Session\Handlers\DatabaseHandler'; for session storage. this works well with other borwsers.
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Models\UserModel;
class User extends BaseController
{
public function login()
{
$data = [];
if ($this->request->getMethod() == 'post') {
$rules = [
'email' => 'required|min_length[6]|max_length[50]|valid_email',
'password' => 'required|min_length[8]|max_length[255]|validateUser[email,password]',
];
$errors = [
'password' => [
'validateUser' => "Email or Password don't match",
],
];
if (!$this->validate($rules, $errors)) {
return view('login', [
"validation" => $this->validator,
]);
} else {
$model = new UserModel();
$user = $model->where('email', $this->request->getVar('email'))
->first();
// Stroing session values
$this->setUserSession($user);
// Redirecting to dashboard after login
return redirect()->to(base_url('dashboard'));
}
}
return view('login');
}
private function setUserSession($user)
{
$data = [
'id' => $user['id'],
'name' => $user['name'],
'phone_no' => $user['phone_no'],
'email' => $user['email'],
'isLoggedIn' => true,
];
session()->set($data);
return true;
}
public function register()
{
$data = [];
if ($this->request->getMethod() == 'post') {
//let's do the validation here
$rules = [
'name' => 'required|min_length[3]|max_length[20]',
'phone_no' => 'required|min_length[9]|max_length[20]',
'email' => 'required|min_length[6]|max_length[50]|valid_email|is_unique[tbl_users.email]',
'password' => 'required|min_length[8]|max_length[255]',
'password_confirm' => 'matches[password]',
];
if (!$this->validate($rules)) {
return view('register', [
"validation" => $this->validator,
]);
} else {
$model = new UserModel();
$newData = [
'name' => $this->request->getVar('name'),
'phone_no' => $this->request->getVar('phone_no'),
'email' => $this->request->getVar('email'),
'password' => $this->request->getVar('password'),
];
$model->save($newData);
$session = session();
$session->setFlashdata('success', 'Successful Registration');
return redirect()->to(base_url('login'));
}
}
return view('register');
}
public function profile()
{
$data = [];
$model = new UserModel();
$data['user'] = $model->where('id', session()->get('id'))->first();
return view('profile', $data);
}
public function logout()
{
session()->destroy();
return redirect()->to('login');
}
}
CodeIgniter4 has its "user agent class" this should help you to be able to validate if you are using IE, I share the documentation and I hope it helps you.
You can validate using that class and redirect with another method.
https://codeigniter.com/user_guide/libraries/user_agent.html

How to ignore unique validation when updating fields in laravel8?

I currently use Laravel 8 and I want to know how do I ignore unique validation when a user is updating their profile? If the user is updating every field except the pageName I don't want it to throw a vaildation error cause the user is already the owner of that pageName. I tried this code but it gives error: ErrorException
Undefined variable: user
$request->validate([
'image' => 'nullable|mimes:jpeg,jpg,png|max:100',
'pageName' => 'nullable|alpha_dash|unique:users,littlelink_name'.$user->id,
'pageColor' => 'nullable',
'pageFontcolor' => 'nullable',
'pageDescription' => 'nullable|regex:/^[\w.\- ]+$/i',
'pagePixiv' => 'nullable|url',
]);
This is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Auth;
use DB;
use App\Models\User;
use App\Models\Button;
use App\Models\Link;
class UserController extends Controller
{
//Statistics of the number of clicks and links
public function index()
{
$userId = Auth::user()->id;
$littlelink_name = Auth::user()->littlelink_name;
$links = Link::where('user_id', $userId)->select('link')->count();
$clicks = Link::where('user_id', $userId)->sum('click_number');
return view('studio/index', ['littlelink_name' => $littlelink_name, 'links' => $links, 'clicks' => $clicks]);
}
//Show littlelink page. example => http://127.0.0.1:8000/+admin
public function littlelink(request $request)
{
$littlelink_name = $request->littlelink;
$id = User::select('id')->where('littlelink_name', $littlelink_name)->value('id');
if (empty($id)) {
return abort(404);
}
$information = User::select('littlelink_name', 'littlelink_color', 'littlelink_fontcolor', 'littlelink_pixiv', 'littlelink_description')->where('id', $id)->get();
$links = DB::table('links')->join('buttons', 'buttons.id', '=', 'links.button_id')->select('links.link', 'links.id', 'buttons.name')->where('user_id', $id)->orderBy('up_link', 'asc')->get();
return view('littlelink', ['information' => $information, 'links' => $links, 'littlelink_name' => $littlelink_name]);
}
//Show buttons for add link
public function showButtons()
{
$data['buttons'] = Button::select('name')->get();
return view('studio/add-link', $data);
}
//Save add link
public function addLink(request $request)
{
$request->validate([
'link' => 'required|url',
'button' => 'required'
]);
$link = $request->link;
$button = $request->button;
$userId = Auth::user()->id;
$buttonId = Button::select('id')->where('name' , $button)->value('id');
$links = new Link;
$links->link = $link;
$links->user_id = $userId;
$links->button_id = $buttonId;
$links->save();
return back()->with('message', 'Link Added');
}
//Count the number of clicks and redirect to link
public function clickNumber(request $request)
{
$link = $request->link;
$linkId = $request->id;
if(empty($link && $linkId))
{
return abort(404);
}
Link::where('id', $linkId)->increment('click_number', 1);
return redirect()->away($link);
}
//Show link, click number, up link in links page
public function showLinks()
{
$userId = Auth::user()->id;
$data['links'] = Link::select('id', 'link', 'click_number', 'up_link')->where('user_id', $userId)->orderBy('created_at', 'desc')->paginate(10);
return view('studio/links', $data);
}
//Delete link
public function deleteLink(request $request)
{
$linkId = $request->id;
Link::where('id', $linkId)->delete();
return back();
}
//Raise link on the littlelink page
public function upLink(request $request)
{
$linkId = $request->id;
$upLink = $request->up;
if($upLink == 'yes'){
$up = 'no';
}elseif($upLink == 'no'){
$up = 'yes';
}
Link::where('id', $linkId)->update(['up_link' => $up]);
return back();
}
//Show link to edit
public function showLink(request $request)
{
$linkId = $request->id;
$link = Link::where('id', $linkId)->value('link');
$buttons = Button::select('name')->get();
return view('studio/edit-link', ['buttons' => $buttons, 'link' => $link, 'id' => $linkId]);
}
//Save edit link
public function editLink(request $request)
{
$request->validate([
'link' => 'required|url',
'button' => 'required',
]);
$link = $request->link;
$button = $request->button;
$linkId = $request->id;
$buttonId = Button::select('id')->where('name' , $button)->value('id');
Link::where('id', $linkId)->update(['link' => $link, 'button_id' => $buttonId]);
return redirect('/studio/links');
}
//Show littlelinke page for edit
public function showPage(request $request)
{
$userId = Auth::user()->id;
$data['pages'] = User::where('id', $userId)->select('littlelink_name', 'littlelink_color', 'littlelink_fontcolor', 'littlelink_pixiv', 'littlelink_description')->get();
return view('/studio/page', $data);
}
//Save littlelink page (name, description, logo)
public function editPage(request $request)
{
$request->validate([
'image' => 'nullable|mimes:jpeg,jpg,png|max:100',
'pageName' => 'nullable|alpha_dash|unique:users,littlelink_name'.$user->id,
'pageColor' => 'nullable',
'pageFontcolor' => 'nullable',
'pageDescription' => 'nullable|regex:/^[\w.\- ]+$/i',
'pagePixiv' => 'nullable|url',
]);
$userId = Auth::user()->id;
$littlelink_name = Auth::user()->littlelink_name;
$profilePhoto = $request->file('image');
$pageName = $request->pageName;
$pageColor = $request->pageColor;
$pageFontcolor = $request->pageFontcolor;
$pageDescription = $request->pageDescription;
$pagePixiv = $request->pagePixiv;
User::where('id', $userId)->update(['littlelink_name' => $pageName, 'littlelink_color' => $pageColor, 'littlelink_fontcolor' => $pageFontcolor, 'littlelink_pixiv' => $pagePixiv, 'littlelink_description' => $pageDescription]);
if(!empty($profilePhoto)){
$profilePhoto->move(public_path('/img'), $littlelink_name . ".png");
}
return back()->with('message', 'Saved');
}
//Show user (name, email, password)
public function showProfile()
{
$userId = Auth::user()->id;
$data['profile'] = User::where('id', $userId)->select('name', 'email')->get();
return view('/studio/profile', $data);
}
//Save user (name, email, password)
public function editProfile(request $request)
{
$request->validate([
'name' => 'required|unique:users',
'email' => 'required|email|unique:users',
'password' => 'required|min:8',
]);
$userId = Auth::user()->id;
$name = $request->name;
$email = $request->email;
$password = Hash::make($request->password);
User::where('id', $userId)->update(['name' => $name, 'email' => $email, 'password' => $password]);
return back();
}
}
Anyone know how to fix this?
You can change your code to the following
$userId = Auth::user()->id;
$request->validate([
'image' => 'nullable|mimes:jpeg,jpg,png|max:100',
'pageName' => 'nullable|alpha_dash|unique:users,littlelink_name,'.$userId,
'pageColor' => 'nullable',
'pageFontcolor' => 'nullable',
'pageDescription' => 'nullable|regex:/^[\w.\- ]+$/i',
'pagePixiv' => 'nullable|url',
]);
you can use the Rule object to make that validation:
'pageName' => ['nullable','alpha_dash', Rule::unique('users','littlelink_name')->ignore($user->id)

Undefined variable in Lumen

I am going to send email using gmail smtp in lumen, Everything working fine but one variable is always undefined, Please let me know where i am wrong
Here is my code
<?php
namespace App\Services;
use Illuminate\Support\Facades\Mail;
class MailService
{
public static function send($mail_to = '', $title = '', $content = '') {
Mail::send('mail', ['title' => $title, 'content' => $content], function ($message) {
$message->from('noreply#gmail.com', 'Test Mail');
$message->to($mail_to);
});
}
}
Here is the Controller
public function register(Request $request)
{
$rules = [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:5',
'phone' => 'required|numeric|min:10',
'business_name' => 'required|unique:users',
'business_type' => 'required'
];
$this->validate($request, $rules);
$data = $request->all();
$hashPassword = Hash::make($data['password']);
$data['password'] = $hashPassword;
$data['is_activated'] = 'false';
$pin = mt_rand(1000, 9999);
$token = hash("sha256", $pin);
$data['token'] = $token;
$data['otp'] = $pin;
$user = User::create($data);
if ($user) {
MailService::send($request->input('email'), 'OTP', $pin);
return response()->json(['response' => true, 'message' => 'User registered Successfully', 'token' => $token], 201);
} else {
return response()->json(['response' => false, 'message' => ' Please check your credentials, Try again'], 400);
}
}
Here is the error
{message: "Undefined variable: mail_to", exception: "ErrorException", file: "D:\xampp\htdocs\api\app\Services\MailService.php", line: 12, trace: Array(28)}
exception: "ErrorException"
file: "D:\xampp\htdocs\api\app\Services\MailService.php"
line: 12
message: "Undefined variable: mail_to"
You are missing $mail_to. you need to use it in function then you may use it otherwise you would get an undefined variable error as you're getting it now.
use($mail_to)
Here your code looks like below.
public static function send($mail_to = '', $title = '', $content = '') {
Mail::send('mail', ['title' => $title, 'content' => $content], function ($message) use($mail_to) {
$message->from('noreply#gmail.com', 'Test Mail');
$message->to($mail_to);
});
}

Use of undefined constant while storing data from form

I have created a model
Review.php
and resource controller for it
ReviewController.php
with route
Route::resource('review','ReviewController');
and created a form to get the values. My store method:
public function store(Request $request)
{
$this->validate($request, [
'fullname' => 'required|max:255',
'email' => 'required',
'country' => 'required',
'tourname' => 'required',
'content' => 'required'
]);
$reviews = new Review;
$reviews->name = $request->fullname;
$reviews->email = $request->email;
$reviews->country = $request->country;
$reviews->content = $request->content;
$reviews->tour_id = $request->tourname;
if($request->hasFile('clidentpp')){
$image = $request->file('clidentpp');
$filename = time().'.'.$image->getClientOriginalName();
$location = public_path('images/client_review'.$filename);
Image::make($image)->resize(128, 128)->save($location);
$reviews->path = $location;
}
$reviews->save();
Session::flash('success','Thank you for your review !');
return back()->withInput(['tab'=>'complete']);
}
I'm getting error
Use of undefined constant reviews - assumed 'reviews'
pointing at line $reviews = new Review;. I tried changing$reviews to $review also still no luck.
It should be $reviews = new Review();
Try this.
$review[] = '';
$review['name'] = $request->fullname;
$review['email'] = $request->email;
...
Review::create($review);

Categories