Error in Custom Blade Directives with array as parameter - laravel-5

In my Laravel 5.7 app I want to use Custom Blade Directives and to pass an array in this directive
as there could be different access, like :
#loggedUserHasAccess([USER_ACCESS_ADMIN])
<div class="col">
<a class="social-inner" href="{{ route('admin.dashboard') }}" >
<span class="icon"></span><span>Backend</span>
</a>
</div>
#endLoggedUserHasAccess
And in app/Providers/AppServiceProvider.php :
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
...
\Blade::directive('loggedUserHasAccess', function (array $accessArray) {
$condition = false;
if (Auth::check()) {
$loggedUser = Auth::user();
$usersGroups = User::getUsersGroupsByUserId($loggedUser->id, false);
foreach ($usersGroups as $next_key => $nextUsersGroup) {
if (in_array($nextUsersGroup->group_id, $accessArray)) {
$condition = true;
}
}
}
return "<?php if ($condition) { ?>";
});
Blade::directive('endLoggedUserHasAccess', function () {
return "<?php } ?>";
});
But I got syntax error : https://imgur.com/a/I5s1TmQ
USER_ACCESS_ADMIN is defined in bootstrap/app.php.
looks like my syntax is invalid, but which is valid ?
Thanks!

Related

404 on add to cart laravel

i have this situation on add to cart when i want to add to cart i am getting 404 error,
this is my route
Route::get('/add-to-cart/{product}', [CartController::class, 'addToCart'])->name('add.cart');
Route::get('/remove/{id}', [CartController::class, 'removeFromCart'])->name('remove.cart');
Route::get('/change-qty/{product}', [CartController::class, 'changeQty'])->name('change_qty');
This is controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Products;
class CartController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
return view('cart.index');
}
public function addToCart(Products $product)
{
$cart = session()->get('cart');
if (!$cart) {
$cart = [$product->id => $this->sessionData($product)];
return $this->setSessionAndReturnResponse($cart);
}
if (isset($cart[$product->id])) {
$cart[$product->id]['quantity']++;
return $this->setSessionAndReturnResponse($cart);
}
$cart[$product->id] = $this->sessionData($product);
return $this->setSessionAndReturnResponse($cart);
}
public function changeQty(Request $request, Products $product)
{
$cart = session()->get('cart');
if ($request->change_to === 'down') {
if (isset($cart[$product->id])) {
if ($cart[$product->id]['quantity'] > 1) {
$cart[$product->id]['quantity']--;
return $this->setSessionAndReturnResponse($cart);
} else {
return $this->removeFromCart($product->id);
}
}
} else {
if (isset($cart[$product->id])) {
$cart[$product->id]['quantity']++;
return $this->setSessionAndReturnResponse($cart);
}
}
return back();
}
public function removeFromCart($id)
{
$cart = session()->get('cart');
if (isset($cart[$id])) {
unset($cart[$id]);
session()->put('cart', $cart);
}
return redirect()->back()->with('success', "Removed from Cart");
}
protected function sessionData(Products $product)
{
return [
'name' => $product->nume,
'quantity' => 1,
'price' => $product->pret,
];
}
protected function setSessionAndReturnResponse($cart)
{
session()->put('cart', $cart);
return redirect()->route('cart')->with('success', "Added to Cart");
}
This is what i have in view file:
<a class="theme_btn add_cart w-100" href="{{route('add.cart', [$produs->id])}}">add to cart
<span class="theme_btn_eff"></span>
</a>
In my loop when i fetch products, on click is redirecting me to 404 page without getting an error, i was trying to get dd($product) into controller but i get again 404.
Change this line
<a class="theme_btn add_cart w-100"
href="{{ route('add.cart', [$produs->id]) }}" >add to cart
<span class="theme_btn_eff"></span>
</a>
To This
<a class="theme_btn add_cart w-100"
href="{{ route('add.cart', ['product' => $produs->id]) }}" >add to cart
<span class="theme_btn_eff"></span>
</a>
In routes file you have passed route parameter naming {product} in url /add-to-cart/{product}, hence you need to mention it in view file as well {{ route('add.cart', ['product' => $produs->id]) }} thats the naming convention laravel follows
Route::get('/add-to-cart/{product}', [CartController::class, 'addToCart'])->name('add.cart');

Custom blade directives not working - syntax error, unexpected ')'

I'm trying to create a blade directive that checks if the User is logged in AND has an activated account. In our database, we have a user_status column with 0: pending, 9 active.
// AppServiceProvider.php
public function boot()
{
Blade::directive('active', function () {
$condition = false;
// check if the user is authenticated
if (Auth::check()) {
// check if the user has a subscription
if(auth()->user()->getStatus() == 9) {
$condition = true;
} else {
$condition = false;
}
}
return "<?php if ($condition) { ?>";
});
Blade::directive('inactive', function () {
return "<?php } else { ?>";
});
Blade::directive('endactive', function () {
return "<?php } ?>";
});
}
// welcome.blade.php
#active
<p>User is active</p>
#inactive
<p>User is inactive</p>
#endactive
I have included this getStatus() function on my User.php model.
public function getStatus() {
return $this->user_status;
}
I can also use the Trait MustActivateAccount, which includes this feature:
/**
* Determine if the user has activated account.
*
* #return bool
*/
public function hasActivatedAccount()
{
return $this->user_status == 9;
}
This blade directive when added to the page says this error:
Facade\Ignition\Exceptions\ViewException
syntax error, unexpected ')'
Am I not escaping correctly in the AppServiceProvider.php file and if so where and how?
You can try this in your blade template
#if(Auth()->user()->user_status == 9)
<p>User is active</p>
#else
<p>User is inactive</p>
#endif
I had the same issue and the solution turned out to be the boolean $condition variable that had to be set as a string. $condition = "true"; and not $condition = true.
This makes sense since the boolean would not echo out. Thus it would be <?php if() { ?> and not <?php if(true) { ?>.
See below (current version 6.18.41):
// check for Providers
Blade::directive('provider', function () {
// check if the user has the correct type
$condition = Auth::user()->type === "provider" ? "true" : "false"; // ... and not boolean
return "<?php if (" . $condition . ") { ?>";
});
Blade::directive('endprovider', function () {
return "<?php } ?>";
});
... and run: php artisan view:clear

laravel-5.8:The POST method is not supported for this route. Supported methods: GET, HEAD

hi m trying to add products in cart but it says: The POST method is not supported for this route. Supported methods: GET, HEAD.. (View: \resources\views\product\detail.blade.php), I wants that by clicking the addtocart it redirect me to that age with products,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,...…………………………………..,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
route:
Route::get('cart', 'Admin\ProductController#cart')->name('product.cart');
Route::get('/addToCart/{product}', 'Admin\ProductController#addToCart')->name('addToCart');
controller:
public function cart()
{
if (!Session::has('cart')) {
return view('products.cart');
}
$cart = Session::has('cart');
return view('product.cart', compact('cart'));
}
public function addToCart(Product $product, Request $request)
{
if(empty(Auth::user()->email)){
$data['email'] = '';
}else{
$data['email'] = Auth::user()->email;
}
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$qty = $request->qty ? $request->qty : 1;
$cart = new Cart($oldCart);
$cart->addProduct($product);
Session::put('cart', $cart);
return redirect()->back()->with('flash_message_success', 'Product $product->title has been successfully added to Cart');
}
view:
<form method="POST" action="{{ route('addToCart') }}" enctype="multipart/form-data">
<div class="btn-addcart-product-detail size9 trans-0-4 m-t-10 m-b-10">
#if($product->product_status == 1)
<!-- Button -->
<button class="flex-c-m sizefull bg1 bo-rad-23 hov1 s-text1 trans-0-4">
Add to Cart
</button>
#else Out Of Stock #endif
</div>
</form>
model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cart
{
private $contents;
private $totalQty;
private $contentsPrice;
public function __construct($oldCart){
if ($oldCart) {
$this->contents = $oldCart->contents;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function addProduct($product, $qty){
$products = ['qty' => 0, 'price' => $product->price, 'product' => $product];
if ($this->contents) {
if (array_key_exists($product->slug, $this->contents)) {
$product = $this->contents[$product->slug];
}
}
$products['qty'] +=$qty;
$products['price'] +=$product->price * $product['qty'];
$this->contents[$product->slug] = $product;
$this->totalQty+=$qty;
$this->totalPrice += $product->price;
}
public function getContents()
{
return $this->contents;
}
public function getTotalQty()
{
return $this->totalQty;
}
public function getTotalPrice()
{
return $this->totalPrice;
}
}
First of all your form method in the view is POST but you don't have a post route.
Second, the route that you have defined expect a parameter(product) you can change the form action as below BUT I think you want to send the user to another page so you can use a link instead of form.
Here's the form action:
action="{{ route('addToCart', $product->id) }}"
And if you want to use link, you can do something like this:
.....
Your method should be POST. In the form, you're calling it Post method but in route.php file, you defined as get to change it as Route::post
Route::post('/addToCart/{product}', 'Admin\ProductController#addToCart')->name('addToCart');
In addition, your route.php file expecting {product} so you need to pass it in form route so your action be like {{ route('addToCart',$product->id) }}
<form method="POST" action="{{ route('addToCart',$product->id) }}" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

How to use x-editable with CodeIgniter?

I would like to understand using x-editable in my CodeIgniter first project. I tried to read x-editable docs but I'm beginner in JavaScript too so I can't understand
I make simple controller to collect data from JavaScript but I didn't complete it or data not updated in database.
$('#username').editable({
type: 'text',
pk: 1,
url: '/post',
title: 'Enter username'
});
How to get submitted data in controller or model to process database update query
I want to passing data submitted from x-editable to model to update it in database.
You can follow this simple steps
Assume that $userId = 5 ; $username = "admin";
Consider you html look like this
<a type="text" name="username" onclick="setEditable(this);" data-pk="<?php echo $userId ;?>" data-placeholder="Enter Username" data-name="username" data-type="text" data-url="<?php echo site_url();?>user/updateUserName" data-value="<?php echo $username ;?>" data-prev="admin" data-title="Enter Username"><?php $username; ?></a>
In Javascript code write following
$.fn.editable.defaults.mode = 'inline';
function setEditable(obj) {
$(obj).editable({
emptytext: $(obj).attr('data-value'),
toggle: 'dblclick',
mode: 'inline',
anim: 200,
onblur: 'cancel',
validate: function(value) {
/*Add Ur validation logic and message here*/
if ($.trim(value) == '') {
return 'Username is required!';
}
},
params: function(params) {
/*originally params contain pk, name and value you can pass extra parameters from here if required */
//eg . params.active="false";
return params;
},
success: function(response, newValue) {
var result = $.parseJSON(response);
$(obj).parent().parent().find('.edit-box').show();
$(obj).attr('data-value', result.username);
$(obj).attr('data-prev', result.username);
},
error: function(response, newValue) {
$(obj).parent().parent().find('.edit-box').hide();
if (!response.success) {
return 'Service unavailable. Please try later.';
} else {
return response.msg;
}
},
display: function(value) {
/*If you want to truncate*/
var strName = strname !== '' ? strname : $(obj).attr('data-value');
var shortText = '';
if (strName.length > 16)
{
shortText = jQuery.trim(strName).substring(0, 14).split("").slice(0, -1).join("") + "...";
}
else {
shortText = strName;
}
$(this).text(shortText);
}
});
$(obj).editable('option', 'value', $(obj).attr('data-value'));
}
In Controller site
<?php
class User extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function updateUserName()
{
$this->load->model('user_model');
if ($this->input->is_ajax_request()) {
$valueStr = $this->input->get_post('value') ? $this->input->get_post('value') : '';
$new_nameStr = trim($valueStr);
$result_arr['username'] = $new_nameStr;
$userId = $this->input->get_post('pk') ? $this->input->get_post('pk') : '';
$data['username'] = $new_nameStr;
$result_arr['username'] = $new_nameStr;
$this->user_model->userUpdateFunction($data, $userId);
}
echo json_encode($result_arr);
exit;
}
}
You can change editable mode , i have set inline only
First of all, this question is about AJAX and JavaScript/jQuery, not Codeigniter.
Basically, the code that you wrote is about posting data with AJAX. First, you need to create a controller and model, then you can post data with AJAX. I'm adding a sample code:
Controller file:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Sample extends CI_Controller {
function __construct() {
parent::__construct();
$this ->load ->model('modelfolder/sample_model');
}
public function index() {
$this->sample_model->sampleFunction();
}
}
Model File:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Sample_model extends CI_Model {
function sampleFunction() {
$data = array('fieldName' => $this->input->post('userName', TRUE));
$this->db->where('id', $this->input->post('userId', TRUE));
$this->db->update('tableName', $data);
return true;
}
}
routes.php File:
$route['demoPost'] = 'controller_folder/sample';
View File's HTML part:
<form id="sampleForm">
<input type="text" name="userId" />
<input type="text" name="userName" />
</form>
View File's AJAX part:
$(document).ready(function(){
$("#sampleForm").submit(
function(){
$.ajax({
type: "POST",
url: "<?php echo site_url('demoPost'); ?>",
data: $("#sampleForm").serialize(),
});
});
});

Keeping modal dialog open after validation error laravel

So basically I have a blade.php, controller page and a form request page(validation). I'm trying to keep my modal dialog open if there is an error but I just cant figure it out, what part of code am I missing out on or needs to be changed?
blade.php
<div id="register" class="modal fade" role="dialog">
...
<script type="text/javascript">
if ({{ Input::old('autoOpenModal', 'false') }}) {
//JavaScript code that open up your modal.
$('#register').modal('show');
}
</script>
Controller.php
class ManageAccountsController extends Controller
{
public $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function index()
{
$users = User::orderBy('name')->get();
$roles = Role::all();
return view('manage_accounts', compact('users', 'roles'));
}
public function register(StoreNewUserRequest $request)
{
// process the form here
$this->userRepository->upsert($request);
Session::flash('flash_message', 'User successfully added!');
//$input = Input::except('password', 'password_confirm');
//$input['autoOpenModal'] = 'true'; //Add the auto open indicator flag as an input.
return redirect()->back();
}
}
class UserRepository {
public function upsert($data)
{
// Now we can separate this upsert function here
$user = new User;
$user->name = $data['name'];
$user->email = $data['email'];
$user->password = Hash::make($data['password']);
$user->mobile = $data['mobile'];
$user->role_id = $data['role_id'];
// save our user
$user->save();
return $user;
}
}
request.php
class StoreNewUserRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
// create the validation rules ------------------------
return [
'name' => 'required', // just a normal required validation
'email' => 'required|email|unique:users', // required and must be unique in the user table
'password' => 'required|min:8|alpha_num',
'password_confirm' => 'required|same:password', // required and has to match the password field
'mobile' => 'required',
'role_id' => 'required'
];
}
}
Laravel automatically checks for errors in the session data and so, an $errors variable is actually always available on all your views. If you want to display a modal when there are any errors present, you can try something like this:
<script type="text/javascript">
#if (count($errors) > 0)
$('#register').modal('show');
#endif
</script>
Put If condition outside from script. This above is not working in my case
#if (count($errors) > 0)
<script type="text/javascript">
$( document ).ready(function() {
$('#exampleModal2').modal('show');
});
</script>
#endif
for possibly multiple modal windows you can expand Thomas Kim's code like following:
<script type="text/javascript">
#if ($errors->has('email_dispatcher')||$errors->has('name_dispatcher')|| ... )
$('#register_dispatcher').modal('show');
#endif
#if ($errors->has('email_driver')||$errors->has('name_driver')|| ... )
$('#register_driver').modal('show');
#endif
...
</script>
where email_dispatcher, name_dispatcher, email_driver, name_driver
are your request names being validated
just replace the name of your modal with "login-modal". To avoid error put it after the jquery file you linked or jquery initialized.
<?php if(count($login_errors)>0) : ?>
<script>
$( document ).ready(function() {
$('#login-modal').modal('show');
});
</script>
<?php endif ?>

Resources