Laravel : Condition on route - php

I have an application using Laravel in backend.
In web.php, I'm defining the following route :
Route::get('/customize/{id}', function () {
if (Profile::where('user_id', User::find(4))) {
return true;
}
return false;
});
Basically I want for example when user_id = 4, return true. {id} is the id of the profile. So if the profile has as user_id of 4, the link will return true, else it's false.
For some reason whatever the value I'm setting in user::find() it returns true.
Example of the profile table :

Try this code:
Route::get('/customize/{id}', function () {
if (Profile::where('user_id', User::find(4))->first()) {
return true;
}
return false;
});
By adding first() you will select only one record or null, the result will be true or false.

Try it first
Hope it will helps
You write a subquery which is User::find(4) it will give you an collection object and in your main query you need to check is it exit or not with where condition. So from you need to get id from from your object User::find(4)->id then it can match with user_id;
Route::get('/customize/{id}', function () {
if (Profile::query()->where('user_id','=', User::query()->find(1)->id)->exists()) {
return 'true';
}
return 'false';
});

I just like to add, that Route::fallback() only handles the GET method:
public function fallback($action)
{
$placeholder = 'fallbackPlaceholder';
return $this->addRoute(
'GET', "{{$placeholder}}", $action
)->where($placeholder, '.*')->fallback();
}
If you want to build a fallback for any other HTTP method, than you would have to use an other way:
Route::any('{fallbackPlaceholder}', $action)->where(
'fallbackPlaceholder', '.*'
)->fallback();

Related

Check if token expired in Laravel

I have table tokens with columns: user_id, token, expires_at.
Example:
I have token: 12345, for me, and he expires at: 2018-06-05
When I generate new token, I generate up to 7 days..
How I can check this in model?
I tryied do with scope in model:
public function scopeExpired($query) {
return $this->where('expires_at', '<=', Carbon::now())->exists();
}
But not working. Always false..
I've always done stuff like this the following way. Note that you need the expires_at field as an attribute on your model.
// Probably on the user model, but pick wherever the data is
public function tokenExpired()
{
if (Carbon::parse($this->attributes['expires_at']) < Carbon::now()) {
return true;
}
return false;
}
Then from wherever you can call:
$validToken = $user->tokenExpired();
// Or realistically
if ($user->tokenExpired()) {
// Do something
}

How to pass variables from controller to show their values in blade file

I want to show variables value in blade file. Below is the controller code:-
public function ClientListReviews()
{
// to show client list get data from users booking table
$select_clientlist =
DB::table('users_booking')>where('service_provider', '=', 1)->get();
if(count($select_clientlist) > 0)
{
return view('client-database')->with($select_clientlist);
}
else
{
return view('client-database')->withMessage('No Details Found');
}
}
I want to show the values coming in $select_clientlist variable. Below is the code in my blade file:-
#foreach($select_clientlist as $clientlist)
{{$clientlist->firstname}}
#endforeach
And below is the route file code:-
Route::post('client_list_ajax','ClientDatabase\ClientdatabaseController#ClientListReviews');
I am receiving error.
What am I doing wrong?
Pass the variable using compact method
return View::make('myviewfolder.myview', compact('view1','view2','view3'));
view1,view2,view3 are variable names
Since you only pass the variable when there is records wrap your for each inside isset
if (isset($select_clientlist)) {
foreach($select_clientlist as $clientlist) {
}
}
your query should be like this . you may be forget SELECT statement
$select_clientlist = DB::table('users_booking')->select('*')->where('service_provider', '=', 1)->get();
Either use as
return view('client-database')->with('select_clientlist',$select_clientlist);
Or
return view('client-database',compact('select_clientlist'));
Also add in select_clientlist else part to prevent undefined error
public function ClientListReviews()
{
// to show client list get data from users booking table
$select_clientlist =
DB::table('users_booking')>where('service_provider', '=', 1)->get();
if(count($select_clientlist) > 0)
{
return view('client-database')->with('select_clientlist',$select_clientlist);
}
else
{
$select_clientlist = [];
return view('client-database')->with('select_clientlist',$select_clientlist)->withMessage('No Details Found');
}
}
OR check by isset($select_clientlist) in blade file
$__currentLoopData = isset($select_clientlist)?$select_clientlist:[];
Pass that variable to your view either way .. it should be a collection. If there are no records, it is just empty. The foreach wont run if its empty. Its as simple as that. No need to check if anything is set or is empty etc... just always pass that collection.
public function ClientListReviews()
{
$select_clientlist = DB::table('users_booking')->where('service_provider', 1)->get();
$view = view('client-database', compact('select_clientlist'));
if ($select_clientlist->isEmpty()) {
$view->with('message', 'No Details Found');
}
return $view;
}

Laravel - Calling a method on null & returning false if null

I have ACL set up with laravel. I have the following helper:
function user($user_id = null)
{
if (!$user_id) return Auth::user();
return User::where('id', $user_id)->first();
}
I have this helper function so I don't have to type the long Auth::user().
Here's the problem. I have ACL set up so when I do something like the following in my model and the user is not logged in, I get an error.
if (user()->can('edit-blog')) {
echo 'you can edit blog!';
}
This is the error if the user is not logged in:
Call to a member function can() on null
Now, I have the following code everywhere in my site. I am using ACL in almost every view and model and controller. I don't want to have to do something like the following just to not get the error.
if (user() && user()->can('edit-blog')) {
// do stuff
}
How can I return false if there is a "null" error or an exception?
** What I have tried **
I have tried try/catch but it does not do anything:
try {
if (!$user_id) return Auth::user();
return User::where('id', $user_id)->first();
} catch (Exception $ex) {
return false;
}
Thank you for your support.
You need to check if the user is logged in before calling can
if(Auth::check() && user()->can('edit-post')){
Return true;
}else{
Return false;
}

Protect routes dynamically, based on id (laravel, pivot table)

This topic has been discussed a lot here, but I don't get it.
I would like to protect my routes with pivot tables (user_customer_relation, user_object_relation (...)) but I don't understand, how to apply the filter correctly.
Route::get('customer/{id}', 'CustomerController#getCustomer')->before('customer')
now I can add some values to the before filter
->before('customer:2')
How can I do this dynamically?
In the filter, I can do something like:
if(!User::hasAccessToCustomer($id)) {
App::abort(403);
}
In the hasAccessToCustomer function:
public function hasCustomer($id) {
if(in_array($id, $this->customers->lists('id'))) {
return true;
}
return false;
}
How do I pass the customer id to the filter correctly?
You can't pass a route parameter to a filter. However you can access route parameters from pretty much everywhere in the app using Route::input():
$id = Route::input('id');
Optimizations
public function hasCustomer($id) {
if($this->customers()->find($id)){
return true;
}
return false;
}
Or actually even
public function hasCustomer($id) {
return !! $this->customers()->find($id)
}
(The double !! will cast the null / Customer result as a boolean)
Generic approach
Here's a possible, more generic approach to the problem: (It's not tested though)
Route::filter('id_in_related', function($route, $request, $relationName){
$user = Auth::user();
if(!$user->{$relationName}()->find($route->parameter('id')){
App::abort(403);
}
});
And here's how you would use it:
->before('id_in_related:customers')
->before('id_in_related:objects')
// and so on

Form Validation w/ sql + codeigniter

I'm working on creating a callback function in codeigniter to see if a certain record exists in the database, and if it does it'd like it to return a failure.
In the controller the relevent code is:
function firstname_check($str)
{
if($this->home_model->find_username($str)) return false;
true;
}
Then in the model I check the database using the find_username() function.
function find_username($str)
{
if($this->db->get_where('MasterDB', array('firstname' => $str)))
{
return TRUE;
}
return FALSE;
}
I've used the firstname_check function in testing and it works. I did something like
function firstname_check($str)
{
if($str == 'test') return false;
true;
}
And in that case it worked. Not really sure why my model function isn't doing what it should. And guidance would be appreciated.
if($this->home_model->find_username($str)) return false;
true;
Given that code snippet above, you are not returning it true. If that is your code and not a typo it should be:
if($this->home_model->find_username($str)) return false;
return true;
That should fix it, giving that you did not have a typo.
EDIT:
You could also just do this since the function returns true/false there is no need for the if statement:
function firstname_check($str)
{
return $this->home_model->find_username($str);
}
So the solution involved taking the query statement out of if statement, placing it into a var then counting the rows and if the rows was > 0, invalidate.
Although this is a more convoluted than I'd like.
I find your naming kind of confusing. Your model function is called 'find_username' but it searches for a first name. Your table name is called 'MasterDB'. This sounds more like a database name. Shouldn't it be called 'users' or something similar? I'd write it like this :
Model function :
function user_exists_with_firstname($firstname)
{
$sql = 'select count(*) as user_count
from users
where firstname=?';
$result = $this->db->query($sql, array($firstname))->result();
return ((int) $result->user_count) > 0;
}
Validation callback function :
function firstname_check($firstname)
{
return !$this->user_model->user_exists_with_firstname($firstname);
}

Categories