Laravel Redirect with - php

I got a problem when trying to redirect back with some results from my sql.
I got a function:
public function postSearch() {
$validator = Validator::make(Input::all(), array(
'search' => 'required'
)
);
if($validator->fails()) {
return Redirect::route('search')
->withErrors($validator)
->withInput();
} else {
$search = Input::get('search');
$user = User::where('username', 'like', '%' . $search . '%')->get();
if($user->count() >= 1) {
return Redirect::route('search')
->with('user', $user)
->withInput();
} else {
return Redirect::route('search')
->with('global', 'Could not find user.')
->withInput();
}
}
return Redirect::route('search')
->with('global', 'Something went wrong, try again later.');
}
but when select was successful in other my file with this code:
#foreach ($user as $users)
<p>
$users->username;
</p>
#endforeach
i got exception undefined user variable. But when i trying to search what doesnt exists in table, 'global' attribute showing my message.
Any ideas why is that not working?

Well, your error is just fine. The $user variable is not defined so you can't iterate over it.
There are 2 things you can do. In your view, you can check if the variable is set
#if (isset($user)
#foreach ($user as $users)
{{ $user->name }}
#endforeach
#endif
You can also set a default value on your code, but you will also need to always your variable to the view. For example:
$user = array();
return Redirect::route('search')
->with('user', $user)
->with('global', 'Could not find user.')
->withInput();
// you will need the $user on your last redirect too
This should fix your problem.

Related

session lost after reloading in laravel 6

Here is simple sigin method :
LoginController :
public function signin(Request $r)
{
$data['email'] = $r->email;
$data['password'] = md5($r->password);
if ($data['email'] == '' || $data['password'] == '') {
echo 'Please enter email or password.';
} else {
$userInfo = DB::table('users')->where('email', $data['email'])->get()->first();
if ($data['email'] == $userInfo->email && $data['password'] == $userInfo->password) {
$r->session()->put('userData', $data['email']);
$userData = $r->session()->get('userData');
return redirect('/userpanel')->with('status', $userData);
} else {
return redirect('/login');
}
}
}
HomeController :
public function user_index()
{
$data = DB::table('personals')
->join('companies', 'personals.companyId', 'companies.id')
->get();
return view('userDashboard')->with(['data' => $data]);
}
After login this method redirects to the user panel here display the session information. But if I reload here there don't display any session information. In my blade I print session by the following code :
<div class="alert alert-success" class="d-block">
<div id="userEmail" >{{ session('status') }}</div>
</div>
I use it in HomeController and LoginController. But problem is not fix.
Using with you are basically Flashing Data To Session which will remain in session only for next request, that why when you reload you are not getting that that again.
https://laravel.com/docs/5.8/session#flash-data
This is with() implementation, in which it flashes data using flash(), which will be remain for just for next request.
public function with($key, $value = null)
{
$key = is_array($key) ? $key : [$key => $value];
foreach ($key as $k => $v) {
$this->session->flash($k, $v);
}
return $this;
}
Change this code
public function user_index()
{
$data = DB::table('personals')
->join('companies', 'personals.companyId', 'companies.id')
->get();
session(['data' => $data]);
return view('userDashboard');
}
Add this in your blade file.
#if(\Session::has('status'))
<span>{{\Session::get('status')}}</span>
#endif

Laravel output from SQL validation when record not exists

I'm learning Laravel and I have a question that I do not understand.
I'm using query builder to run my own queries and I don't really know how to return error message when there is no record:
public function store()
{
$item = request()->validate([
'item' => 'required|min:6|max:10'
]);
$details = DB::connection('sqlsrv')->table('TABLENAME')->where('ITEMID', '=', $item )->get();
return view('itemdetails.create', compact('details'));
}
So if $details is null I need to return message how to do that? Something like in raw PHP
if(empty($details))
{
throw new Exception('My text')
}
Or check in a blade file:
#if (count($details) != 1)
I don't have a record!
#endif
I tried firstOrFail but looks like this is not working.
Is there any other ways (best ways)?
In controller
$validator = \Validator::make($request->all(), [
'item' => 'required|min:6|max:10'
]);
$details = DB::connection('sqlsrv')->table('TABLENAME')->where('ITEMID', '=', $item )->get();
if (!$details) {
$validator->errors()->add('item', 'Item not found');
}
if ($validator->fails()) {
return redirect()
->back()
->withErrors($validator)
->withInput();
}
return view('itemdetails.create', compact('details'));
}
And in the view file
{{$validator->errors()->first('item')}}
Just use normal if condition will do for Controller
if($details) //True
{
//Redirect to..
}else
{
//Redirect to.. //False
}
For blade you may use #if(count($details)) if true it will display info #else {{No data}} #endif

Laravel error handling when route does not exist

I have a route to show my users' profile in my laravel project. But when you go to an url and fill in a username that does not exist it gives a nasty error, obviously because that username doesn't exist in the database.
Has anyone any idea how I can error handle this?
Here's my route:
Route::get('user/{name}', 'userController#showUser');
Here's my function:
public function showUser($name)
{
$user = User::where('name' , '=', $name)->firstOrFail();
return view('user.show', compact('user'));
}
This is what I've tried but doesn't seem to work since I get this error:
View not found
$user = User::where('name' , '=', $name)->first();
if(!empty($user)){
return view('user.show', compact('user','projects'));
}else{
return view('user');
}
Try this
$user = User::where('name' , '=', $name)->first();
if(!empty($user)){
return view('user.show', compact('user','projects'));
}else{
return redirect()->route('/routeWhereYouWannaSend');
}
For more info read HTTP Responses
2nd Solution: If you want to redirect to Homepage on route(s) that doesn't exist at all Link
you can use first method to get username from user table
public function showUser($name){
$user = User::where('name' , '=', $name)->first();
if(!empty($user)){
return view('user.show', compact('user'));
}
}
}
Lets make sure your view file is in user folder

Laravel Checking If a Record Exists

I am new to Laravel. How do I find if a record exists?
$user = User::where('email', '=', Input::get('email'));
What can I do here to see if $user has a record?
It depends if you want to work with the user afterwards or only check if one exists.
If you want to use the user object if it exists:
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}
And if you only want to check
if (User::where('email', '=', Input::get('email'))->count() > 0) {
// user found
}
Or even nicer
if (User::where('email', '=', Input::get('email'))->exists()) {
// user found
}
if (User::where('email', Input::get('email'))->exists()) {
// exists
}
In laravel eloquent, has default exists() method, refer followed example.
if (User::where('id', $user_id )->exists()) {
// your code...
}
One of the best solution is to use the firstOrNew or firstOrCreate method. The documentation has more details on both.
if($user->isEmpty()){
// has no records
}
Eloquent uses collections.
See the following link: https://laravel.com/docs/5.4/eloquent-collections
Laravel 5.6.26v
to find the existing record through primary key ( email or id )
$user = DB::table('users')->where('email',$email)->first();
then
if(!$user){
//user is not found
}
if($user){
// user found
}
include " use DB " and table name user become plural using the above query like user to users
if (User::where('email', 'user#email.com')->first()) {
// It exists
} else {
// It does not exist
}
Use first(), not count() if you only need to check for existence.
first() is faster because it checks for a single match whereas count() counts all matches.
It is a bit late but it might help someone who is trying to use User::find()->exists() for record existence as Laravel shows different behavior for find() and where() methods. Considering email as your primary key let's examine the situation.
$result = User::find($email)->exists();
If a user record with that email exists then it will return true. However the confusing thing is that if no user with that email exists then it will throw an error. i.e
Call to a member function exists() on null.
But the case is different for where() thing.
$result = User::where("email", $email)->exists();
The above clause will give true if record exists and false if record doesn't exists. So always try to use where() for record existence and not find() to avoid NULL error.
This will check if requested email exist in the user table:
if (User::where('email', $request->email)->exists()) {
//email exists in user table
}
In your Controller
$this->validate($request, [
'email' => 'required|unique:user|email',
]);
In your View - Display Already Exist Message
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Checking for null within if statement prevents Laravel from returning 404 immediately after the query is over.
if ( User::find( $userId ) === null ) {
return "user does not exist";
}
else {
$user = User::find( $userId );
return $user;
}
It seems like it runs double query if the user is found, but I can't seem to find any other reliable solution.
if ($u = User::where('email', '=', $value)->first())
{
// do something with $u
return 'exists';
} else {
return 'nope';
}
would work with try/catch
->get() would still return an empty array
$email = User::find($request->email);
If($email->count()>0)
<h1>Email exist, please make new email address</h1>
endif
Simple, comfortable and understandable with Validator
class CustomerController extends Controller
{
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:customers',
'phone' => 'required|string|max:255|unique:customers',
'password' => 'required|string|min:6|confirmed',
]);
if ($validator->fails()) {
return response(['errors' => $validator->errors()->all()], 422);
}
I solved this, using empty() function:
$user = User::where('email', Input::get('email'))->get()->first();
//for example:
if (!empty($user))
User::destroy($user->id);
you have seen plenty of solution, but magical checking syntax can be like,
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
it will automatically raise an exception with response 404, when not found any related models Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The fingernail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, an Illuminate\Database\Eloquent\ModelNotFoundException will be thrown.
Ref: https://laravel.com/docs/5.8/eloquent#retrieving-single-models
$user = User::where('email', request('email'))->first();
return (count($user) > 0 ? 'Email Exist' : 'Email Not Exist');
This will check if particular email address exist in the table:
if (isset(User::where('email', Input::get('email'))->value('email')))
{
// Input::get('email') exist in the table
}
Shortest working options:
// if you need to do something with the user
if ($user = User::whereEmail(Input::get('email'))->first()) {
// ...
}
// otherwise
$userExists = User::whereEmail(Input::get('email'))->exists();
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}
can be written as
if (User::where('email', '=', Input::get('email'))->first() === null) {
// user doesn't exist
}
This will return true or false without assigning a temporary variable if that is all you are using $user for in the original statement.
I think below way is the simplest way to achieving same :
$user = User::where('email', '=', $request->input('email'))->first();
if ($user) {
// user exist!
}else{
// user does not exist
}
Created below method (for myself) to check if the given record id exists on Db table or not.
private function isModelRecordExist($model, $recordId)
{
if (!$recordId) return false;
$count = $model->where(['id' => $recordId])->count();
return $count ? true : false;
}
// To Test
$recordId = 5;
$status = $this->isModelRecordExist( (new MyTestModel()), $recordId);
Home It helps!
The Easiest Way to do
public function update(Request $request, $id)
{
$coupon = Coupon::where('name','=',$request->name)->first();
if($coupon->id != $id){
$validatedData = $request->validate([
'discount' => 'required',
'name' => 'required|unique:coupons|max:255',
]);
}
$requestData = $request->all();
$coupon = Coupon::findOrFail($id);
$coupon->update($requestData);
return redirect('admin/coupons')->with('flash_message', 'Coupon updated!');
}
Laravel 6 or on the top: Write the table name, then give where clause condition for instance where('id', $request->id)
public function store(Request $request)
{
$target = DB:: table('categories')
->where('title', $request->name)
->get()->first();
if ($target === null) { // do what ever you need to do
$cat = new Category();
$cat->title = $request->input('name');
$cat->parent_id = $request->input('parent_id');
$cat->user_id=auth()->user()->id;
$cat->save();
return redirect(route('cats.app'))->with('success', 'App created successfully.');
}else{ // match found
return redirect(route('cats.app'))->with('error', 'App already exists.');
}
}
If you want to insert a record in the database if a record with the same email not exists then you can do as follows:
$user = User::updateOrCreate(
['email' => Input::get('email')],
['first_name' => 'Test', 'last_name' => 'Test']
);
The updateOrCreate method's first argument lists the column(s) that uniquely identify records within the associated table while the second argument consists of the values to insert or update.
You can check out the docs here: Laravel upserts doc
You can use laravel validation if you want to insert a unique record:
$validated = $request->validate([
'title' => 'required|unique:usersTable,emailAddress|max:255',
]);
But also you can use these ways:
1:
if (User::where('email', $request->email)->exists())
{
// object exists
} else {
// object not found
}
2:
$user = User::where('email', $request->email)->first();
if ($user)
{
// object exists
} else {
// object not found
}
3:
$user = User::where('email', $request->email)->first();
if ($user->isNotEmpty())
{
// object exists
} else {
// object not found
}
4:
$user = User::where('email', $request->email)->firstOrCreate([
'email' => 'email'
],$request->all());
$userCnt = User::where("id",1)->count();
if( $userCnt ==0 ){
//////////record not exists
}else{
//////////record exists
}
Note :: Where condition according your requirements.
Simply use this one to get true or false
$user = User::where('email', '=', Input::get('email'))->exists();
if you want $user with result you can use this one,
$user = User::where('email', '=', Input::get('email'))->get();
and check result like this,
if(count($user)>0){}
Other wise you can use like this one,
$user = User::where('email', '=', Input::get('email'));
if($user->exists()){
$user = $user->get();
}
The efficient way to check if the record exists you must use is_null method to check against the query.
The code below might be helpful:
$user = User::where('email', '=', Input::get('email'));
if(is_null($user)){
//user does not exist...
}else{
//user exists...
}
It's simple to get to know if there are any records or not
$user = User::where('email', '=', Input::get('email'))->get();
if(count($user) > 0)
{
echo "There is data";
}
else
echo "No data";

Laravel 4 error passing not working

I am trying to make a authentication system and the only issue that I am having is that it will not display the errors if the wrong creds are used. It shows the error when one of the fields is empty but not when they are both filled with wrong info. Can someone help me figure out what is wrong? Thanks for all the help!
Here is my view
{{ Form::open([
"route"=>"user/login",
"autocomplete"=>"off"
]) }}
{{ Form::label("username", "Username") }}
{{ Form::text("username", Input::old("username"), [
"placeholder"=>"Username"
]) }}
{{ Form::label("password", "Password") }}
{{ Form::password("password", [
"placeholder"=>"Password"
]) }}
#if($error = $errors->first("password"))
<div class="error">
{{ $error }}
</div>
#endif
{{ Form::submit("Login") }}
{{ Form::close() }}
here is the controller
<?php
use Illuminate\Support\MessageBag;
class UserController extends BaseController
{
public function loginAction()
{
$errors = new MessageBag();
if($old = Input::old("errors")) {
$errors = $old;
}
$data = [
"errors"=>$errors
];
if(Input::server("REQUEST_METHOD") == "POST") {
$validator = Validator::make(Input::all(), [
"username"=>"required",
"password"=>"required"
]);
if($validator->passes()) {
$credentials = [
"username"=>Input::get("username"),
"password"=>Input::get("password")
];
if(Auth::attempt($credentials)) {
//return Redirect::route("user/login");
echo "login success";
}
} else {
echo "Login failed";
$data["errors"] = new MessageBag([
"password"=>[
"Username and/or password invalid."
]
]);
$data["username"] = Input::get("username");
return Redirect::route("user/login")
->withInput($data);
}
}
return View::make("user/login", $data);
}
}
It looks like you are not displaying any message if the authentication fails. Auth::attempt() will try to match the username and password and if it fails it should add something to the errors array.
if(Auth::attempt($credentials)) {
//return Redirect::route("user/login");
echo "login success";
}
else // add this
{
echo 'login failed - username and/or password provided are not correct';
}
That said, you probably need to add an else statement here.

Categories