Laravel 5.2 method to check is view exists? - laravel

Is there any method to check if view exists?
Like PHP file_exists, but using internal laravel method for convenience
i want to code like this:
if(__ifViewExist__($view)){
return view($view)->render();
}
return "Page tidak ditemukan";

Yes, an exists() method is available.
if(view()->exists($view)){
return view($view)->render();
}
return "Page tidak ditemukan";

Yes. Using the View facade.
// Return true when welcome.blade.php does not exist in theview folder
View::exists('welcome');
// Return false when login.blade.php does not exist in the view folder
View::exists('login');

try {
return view($view);
} catch (\Exception $e) {
return "Page tidak ditemukan";
}
will be more efficient way

In web.php, you need to type below given code:
Route::get('/Test',function(){
if(View::exists('View'))
{
return view('View.php',['name' => 'Your string']);
}
return "File not found";
});

Related

Want to redirect to a page

I want to redirect to the product page. This is my controller function.
public function RegisterBusiness(Request $request){
DB::beginTransaction();
try {
if(session()->has('user_id')){
$request['mybiz_users_id']=Session()->get('user_id');
}
$this->businessTempService->insertRegisteredBusinessDetails($request);
DB::commit();
return $this->sendResponse('success', 'Registered Successfully, Thank You!', '', 200,route('web.registration.advanced-product-registration'));
} catch (Exception $ex) {
DB::rollback();
Log::error($ex);
return $this->sendResponse('error', 'Something went wrong', '', 422);
}
}
But it is not working.
It loads this page
This is not an error, its a json response , if you redirect to product page then change
return $this->sendResponse('error', 'Something went wrong', '', 422);
to
return view('product.index');
or, with name route :
return route('product');
You should use \request()->expectsJson() to find out whether you need a json response or not.
if (\request()->expectsJson()){
return $this->sendResponse('success', 'Registered Successfully, Thank You!', '', 200,route('web.registration.advanced-product-registration'));
}else{
return back();
}

How to handle native exception in Laravel?

For example, I use:
return User::findOrFail($id);
When row does not exist with $id I get exception.
How I can return this exception in Json response? It returns HTML Laravel page now.
I need something like as:
{"error", "No query results for model"}
From their documentation:
Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail and firstOrFail methods will retrieve the first result of the query. However, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown.
So, you can either catch that exception, or go with the simple Find method. It will return false if not found, so you can handle it accordingly.
return User::find($id);
UPDATE:
Option 1:
try {
return User::findOrFail($id);
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
return json_encode(['error' => 'No query results for model']);
}
Option 2:
$user = User::find($id);
if($user) {
return $user;
}
return json_encode(['error' => 'No query results for model']);
You can handle various types of exceptions, that exception can be handle with a ModelNotFoundException in this case
try{
$user = User::findOrFail($id);
}catch(ModelNotFoundException $e){
return response()->json(['error' => 'User not found'], 400);
}
And there's another way to catch various types of exceptions in the Handler.php located on app/Exceptions/Handler.php there you can catch the exceptions and return whatever you want inside the render function.
For example insede that function you can add this before the return parent::render($request, $e):
if($e instanceof ModelNotFoundException)
{
return new Response(['message' => 'We haven\'t find any data'], 204);
}
You should look in render method of Handler file. You can test exception class here and depending on it return different response in Json format

Advanced control Auth::Check

if the columns in the table value of admin, I want to show the admin page, not water to another page
$type = array('type' =>'Admin');
if (Auth::check($type))
{
return view('admin.index');
}
Auth::logout();
return View::make('admin.auth.login');
You'll have to change your RedirectIfAuthenticated.php file. It's stored in /app/Http/Middleware. In the handle function you can check if the user has a specific value in the database and redirect to another page accordingly.
I solved the problem
public function showLogin()
{
if (Auth::check())
{
if (auth()->user()->type!='Admin')
{
return view('helperpage.admin-yetki');
}
else
{
return view('admin.index');
}
}
return View::make('admin.auth.login');
}

How to redirect index page if user not logged in laravel

Hello i create website in laravel but i facing one problem. The problem is that when user is not log in and user type www.test.com/notifications that time showing error like this
ErrorException (E_UNKNOWN)
Undefined variable: messages (View: /home/test/app/views/message-page.blade.php)
But i want to when user is not log in and enter www.test.com/notifications so user automatic redirect to index page. Please help me i very confuse.
I using the some code in base controller is as follows:
public function checkLoggedIn(){
if(Auth::user()->check()){
return;
}
else {
return Redirect::to("/");
}
}
You should do it this way:
public function checkLoggedIn(){
if (!Auth::check()) {
return Redirect::to("/");
}
return true;
}
However I assume you want to use this function in another controller so then you should do it this way:
$result = $this->checkLoggedIn();
if ($result !== true) {
return $result;
}
to make redirection.
But Laravel have filters so you can easily check if user is logged.
You can just use in your routes.php:
Route::group(
['before' => 'auth'],
function () {
// here you put all paths that requires user authentication
}
);
And you can adjust your filter in app/filters for example:
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::to('/');
}
}
});

CakePHP: why aren't validation errors showing up?

So, validation errors show up in my add action, but not in my edit action. Here are the snippets from my controller:
Here I get validation error messages as expected:
public function add() {
if ($this->request->is('post')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please try again.'));
}
}
$this->set('clients', $this->User->Client->find('list'));
}
But not here:
public function edit($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->User->read(null, $id);
unset($this->request->data['User']['password']);
}
$this->set('user', $this->User->read());
$this->set('clients', $this->User->Client->find('list'));
}
If i recall correctly, using the read() call after a failed save will clear the validation errors.
there.. i found it http://book.cakephp.org/1.3/view/1017/Retrieving-Your-Data#read-1029
Is the setFlash('user could not be saved') message firing?
What's the ouput of debug($this->User->validationErrors) - add it after the setFlash fail message
Does your post array contain all the fields it needs to save? Do you have a required field in your $validate that you don't have in your post array? (Cake will register the error, but won't be able to display it unless you have the field in your form). Or another validate rule that is failing but you aren't displaying the field in your form?

Resources