How to ignore unique validation when updating fields in laravel8? - php

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)

Related

Undefined variable in laravel 9

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 }}

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
]);
}

undefined variable in view using dompdf

I am trying to generate a pdf with DOMPDF. This is my code:
class PDFController extends Controller
{
public function invoice(Request $request) {
// $institution = $this->institution();
// $user = $this->user();
$invoice = array($this->invoice_form($request));
$pdf = PDF::loadView('pdf-generation.invoice', $invoice);
return $pdf->setPaper('a4', 'landscape')->download('invoice.pdf');
//return view('pdf-generation.invoice')->with(['institution' => $institution, 'user' => $user, 'invoice' => $invoice]);
}
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';
$institution = $this->institution();
$user = $this->user();
$array = array(
'invoice_id' => $invoice_id,
'new_date' => $new_date,
'provider' => $provider,
'invoice_number' => $invoice_number,
'due_date' => $new_due_date,
'provider' => $provider,
'institution' => $institution,
'user' => $user
);
return (object) $array;
}
}
And in my pdf-generation.invoice view, I have some html generate but it is not worth to post it all, so I am going to post only one line to give you some idea about the problem:
<span style="font-weight: bold; float: left;">{{$invoice->institution}}</span>
However, it says Undefined variable $invoice.. what could be the problem?
You can compact your variable like this:
$pdf = PDF::loadView('pdf-generation.invoice', compact('invoice'));

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

Hi i get this "Error Call to a member function update() on boolean" when updating image in Laravel

Can someone help me with this Laravel problem?
I get Error Call to a member function update() on boolean, when I edit and update Image for an ad.
So when I create a new Ad the image will store but when updating the Ad with a new image the old image stays and I get this error for this line in storeImage.
private function storeImage($ad){
if (request()->has('image')) {
$ad->update([
'image' => request()->image->store('uploads', 'public'),
]);
$image = Image::make(public_path('storage/' . $ad->image))->fit(300, 300, null, 'top-left');
$image->save();
}
}
This is my AdsController
public function edit($id)
{
$ad = Ad::find($id);
return view('ads.edit_ad', compact('ad', 'id'));
}
public function update(Request $request, $id)
{
$ad = Ad::find($id);
$user_id = Auth::user()->id;
$rules = [
'ad_title' => 'required',
'ad_description' => 'required',
'purpose' => 'required',
'image' => 'sometimes|file|image|max:5000',
];
$this->validate($request, $rules);
$title = $request->ad_title;
$is_negotialble = $request->negotiable ? $request->negotiable : 0;
$data = [
'title' => $request->ad_title,
'description' => $request->ad_description,
'type' => $request->type,
'price' => $request->price,
'purpose' => $request->purpose,
'address' => $request->address,
'user_id' => $user_id,
];
$updated_ad = $ad->update($data);
if ($updated_ad){
$this->storeImage($updated_ad);
}
return redirect()->back()->with('success','Ad Updated');
}
public function destroy(Ad $ad)
{
$ad->delete();
return redirect()->back()->with('success','Ad Deleted');
}
/**
* Listing
*/
public function listing(Request $request){
$ads = Ad::all();
$roles = Role::all();
return view('listing', compact('ads'));
}
public function myAds(){
$user = Auth::user();
$ads = $user->ads()->orderBy('id', 'desc')->paginate(20);
return view('ads.my_ads', compact('ads'));
}
private function storeImage($ad){
if (request()->has('image')) {
$ad->update([
'image' => request()->image->store('uploads', 'public'),
]);
$image = Image::make(public_path('storage/' . $ad->image))->fit(300, 300, null, 'top-left');
$image->save();
}
}
At the bottom of your update() function, try to change this:
if ($updated_ad){
$this->storeImage($updated_ad);
}
to this:
if ($updated_ad){
$this->storeImage($ad);
}
The Eloquent models update() function returns a boolean of whether the update completed successfully. After running the update() function on the $ad variable, it is mutated and contains the updated data, and you can use it as an argument in your storeImage() function.

Categories