المشاركات

عرض المشاركات من أبريل, 2020

Unable to make subquery in laravel 5.1 eloquent

I am trying to get some data using laravel eloquent with subquery, but couldn't make it work. I haven't done this before, so kinda dumb on this. Here is my query: $assignedTeacherSubjectsObj = AssignedSubjectToTeacher::with(['class_info', 'subject', 'section', 'group', 'user' => function($query) { $query->select('user_id', 'full_name', 'phone_no'); }]) ->addSelect(["date_wise_assigned_homework" => Homework::whereColumn('tbl_assigned_subjects_to_teachers.institute_branch_version_id', 'tbl_homeworks.institute_branch_version_id') ->whereColumn('tbl_assigned_subjects_to_teachers.class_id', 'tbl_homeworks.class_id') ->whereColumn('tbl_assigned_subjects_to_teachers.group_id', 'tbl_homeworks.group_id') ->whereColumn('tbl_assigned_subjects_to_teachers.sec...

How to know what columns are presents in a Eloquent query before to execute it in Laravel 5.5?

Im using Laravel 5.5 and I have and QueryBuilder object (from the "Illuminate/Database/Eloquent/Builder" class). I want to set an orderBy sentence into my query, but only if this field is present and exists in the QueryBuilder object (as column in the select section sentence). For example, there is an User model, with the following fields ['id', 'firtsname', 'lastname', 'username','description']. This is my object: Use App\User; $query = User::query(); if ($request->input('sort') != null) { $model_query->orderBy($request->input('sort'), 'ASC'); } $users = $query->get(); When I execute it, works fine (if I send you consistent data, of course). But if I set a column what does not exists, it sends and exception. So, the question is, how I can get the columns to retrieve from my $query object? To validate it, and if it's presents, execute the ordening code. from Newest questions tagged laravel-5 - ...

Laravel custom pagination exception | Undefined property $pageName

Error message : Undefined property: Illuminate\Pagination\LengthAwarePaginator::$pageName I am creating pagination from an array and following is the array. $array = [▼ "A" => 1 "B" => 2 "C" => 3 "D" => 4 "E" => 5 ] And have the following code : public function paginate($items, $perPage = 5, $page = null, $options = []) { $page = $page ?: (Paginator::resolveCurrentPage() ?: 1); $items = $items instanceof Collection ? $items : Collection::make($items); return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options); } and calling the above method like the following : $data = $this->paginate($array); return view('test', ['data' => $data]); And in test view, I've the following to show pagination links: <div> </div> I've no idea what am I missing, I've checked quite a lot. from Newest questions tagged laravel-5 ...

Larave Custom DB Databable

I'm interested in having a Table in my Laravel database, where I can read/write from. However, I don't want it do be affected by php artisan migrate:fresh or php artisan migrate:refresh commands. I want to use it as a custom storage for a dataset, which will be imported in the database and updated when needed but only be readable by Laravel. Thanks in advance. from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3cVVFYC via IFTTT

Custom Sequence Number Generation for Order

I have planned a custom sequence number generation for Order Id using MYSQL stored procedures. Eg, Order id : JWT-000001 Any other suggestion and tips. And let me know if you have already did this in any other method. from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3d7gEI7 via IFTTT

My Laravel 5.2 Session doesn't persist when I access a link from Whatsapp(in particular)

Basically the title. When I share a link from my application on Whatsapp the link redirect to login. Always and only on whatsapp. Discord, facebook etc it does'nt happen. Can someone help with this issue? UPDATE This is the link from Whatsapp <a href="https://mylaravelsite.com.br/somepage/9999" title="https://mylaravelsite.com.br/somepage/9999" target="_blank" rel="noopener noreferrer" class="_3FXB1 selectable-text invisible-space copyable-text">https://mylaravelsite.com.br/somepage/9999</a> from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2KQoqdf via IFTTT

Laravel: Having trouble handling multiple files for upload

I have an image uploader that allows multiple images on the frontend (vue.js). When I send it over to Laravel, it's not hitting my foreach loop. I traced the print logs to be executing up until the foreach loops runs but I'm not sure why it's not going through each one unless that's not the correct way. ** JS ** let formData = new FormData(); this.files.forEach((x,index) => { formData.append("file", x) }); axios.post('/admin/upload', formData, { headers: { 'Content-Type': 'multipart/form-data', } }) **Laravel ** print "outside"; if ($request->hasFile('file')) { print "inside"; $files = $request->file('file'); $stack = []; foreach ($files as $file) { print "Looping"; $fileName = Storage::put('/trace/', file_get_contents($file->getRealPath()), ['visibility' => 'public']); array_push($stack, $f...

How to fix Laravel Api passport not validating?

I followed the instructions to set up Laravel passport. A user table and other tables have been created. I copied a tutorial file for a register controller. I am receiving a success message in postman but no required data was entered and it is not doing any validation. Is there anything else I need to do? <?php namespace App\Http\Controllers\Api; use App\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class AuthController extends Controller { public function register(Request $request) { $validatedData = $request->validate([ 'name'=>'required|max:55', 'email'=>'email|required|unique:users', 'password'=>'required|confirmed' ]); $validatedData['password'] = bcrypt($request->password); $user = User::create($validatedData); $accessToken = $user->createToken('authToken')->accessToken; return r...

Laravel - Midlleware called after controller construct

I have trouble with checkauth controller that are called after SectionsController constructor - from this is extended ReportController and I don't know why it works like this. I try add middleware at the start of SectionController costruct like $this->middleware('checkauth'); but not working too. Middleware <?php namespace App\Http\Middleware; use Closure; use Auth; class CheckAuth { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (!Auth::check()) { return redirect('/admin/login')->withErrors(['message' => 'You need to login before proceeding']); } return $next($request); } } ReportController <?php namespace App\Http\Controllers\RMReport\Form; use App\Http\Controllers\RMReport\SectionsController; use Illuminate\Http\R...

How to write paths for assets in Laravel+vue project to component with language option?

I have pure laravel structure and my image is under: project/resources/assets/dist/img/en/image-en.png project/resources/assets/dist/img/fr/image-fr.png I want to show images from my vue component in: project/resources/assets/js/components/Templates/partials/component.vue What are best option to handle show images in that component? My current solution is: <template> <img src="../../../../dist/img//image-.png"> </template> export default { name:'example' data: { lang: 'en' } } How to remove ../../../../ usage from path? and reuse image path in Vue component. from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2zHZ1Qx via IFTTT

Setting a custom user verification link issue in laravel

I have been trying to send my users a custom verification email in laravel. First I run this php artisan make:notification SendRegisterEmailNotifcation This has created a file called, SendRegisterEmailNotifcation.php inside my App/Notifications . Then Inside my user controller's store method, I called that method after user insertion done. Following is my store function, public function store(Request $request) { request()->validate([ 'name' => ['required', 'alpha','min:2', 'max:255'], 'last_name' => ['required', 'alpha','min:2', 'max:255'], 'email' => ['required','email', 'max:255', 'unique:users'], 'password' => ['required', 'string', 'min:12', 'confirmed','regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$/...

How to add multiple rows for same record in laravel?

image As you can see the image has Add row button . which add multiple rows for one record . I am trying to design database for this but confuse about this step. One thought is I should store this data in the form of json for each column . But I don't think that is a good approach. Please share your ideas How I can add multiple values for same record in database? from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ycRxok via IFTTT

Laravel CreateApiToken for guest users

In Laravel 5.7, we can pass \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class in the web middleware group. This adds the laravel_token cookie for logged in users. Is it possible to also pass a cookie for logged out users, so that we can lock API routes with the client middleware, thus authenticating the app but not necessarily the user? from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2VQqAQd via IFTTT

Laravel email verification link issue

In my laravel application's app url is something like this, admin.site and I'm registering users to my application from the admin panel. And my client portal url is customer.site . Once the admin creates an user from admin panel (admin.site) customer receive an account verification email. But the issue is now I need this verification link to be customer.site/email/... but the current link is like this admin.site/email/... So how can I change this verification link to customer.site Following is my store function for customer controller public function store(Request $request) { request()->validate([ 'name' => ['required', 'alpha','min:2', 'max:255'], 'last_name' => ['required', 'alpha','min:2', 'max:255'], 'email' => ['required','email', 'max:255', 'unique:users'], 'password' => ...

Foreign key mismatch - "password_resets" referencing "users" on dropColumn

I'm trying to drop a column (lets call it fooboo) on 'users' table with migrations and i'm getting the next error: General error: 1 foreign key mismatch - "password_resets" referencing "users" (SQL: INSERT INTO users (id, name, email, password, fooboo, created_at, updated_at) SELECT id, name, email, password, fooboo, created_at, updated_at FROM __temp__users) The up() function in migration class: public function up() { Schema::table('users', function (Blueprint $table) { $table->dropColumn('fooboo'); }); } This column in particular doesn't have any index, FK or anything that could create conflict. It is just a boolean with a default value FALSE . I'm getting this error with sqlite when running my unit tests (phpunit). I can't solve this problem just removing the column on migration class that creates it, i need a new migration to run on production server. Asking our friend google...

Customize email verification link issue in laravel

I have admin portal and customer portal in my laravel based application customer portal: customer.site admin portal :admin.site I have option to register for customers on my customer portal. Once an user register a verification email will be sent to user email with the verification link. sample verification link can be like this: http://customer.site/email/verify/10/2bf6330a5b3693fb6f5380e83e5494f82b87a9f8?expires=1588234415&signature=34ac37e86d1de7e316e717f2e1acf32cd4ee6ed97df56d94496bb2fa79a0f608 so this works perfectly. Now my issue is, When I try to create a customer through the ADMIN portal (admin.site) the user creates successfully and the verification mail also sending successfully to the customer address. But, the activation link is something like this http://admin.site/email/verify/10/2bf6330a5b3693fb6f5380e83e5494f82b87a9f8?expires=1588234415&signature=34ac37e86d1de7e316e717f2e1acf32cd4ee6ed97df56d94496bb2fa79a0f608 so when a cutomer clicks on that link a forbidden pa...

Planning a laravel application - MVC disaster

I am currently creating a small Laravel project. The goal should be. Every User can have 1 or more projects. Every project has data that displayed in Datatables. The Problem. The data for each projects are different in structure (e.g. Addresses, Questionnaire, ...) I have now created a separate model / view / controller for each project. But I think it's not the right way. e.g. 100 users have 2 projects, then I need 200 model / views / controller ??? How could I do better? Thanks in advance for your help. from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2Yib2q0 via IFTTT

How to create a route to show Laravel API relationships?

I am able to use Tinker to see relationship between product and reviews. Results are returned. php artisan tinker >> App\Model\Product::find(1)->reviews How do I create a route and a controller to show this relationship because the show method is already being used to show by ID. Do I use the product controller or the reviews controller? Can I show both ways reviews by product and products by reviews? UPDATED Here is my products data Data: [ { productName: "television", price: null, id: 1 }, Here is my reviews data data: [ { id: 2, customerId: "4", booktitle: null, description: null, likes: null, customer: null, body: null, star: null, productId: "1" }, Here is my review model <?php namespace App; use App\Product; use Illuminate\Database\Eloquent\Model; class Review extends Model { public $timestamps = true; protected $table = 'REVIEWS'; protected $fillable = [ 'booktitle', 'description', 'updated_at...

Laravel change password issue

For Laravel change password I did like this but why it is not working.. I have done login page, registration everything working. But this giving me lot of trouble. Below is my code. $returnValue = DB::table('users')->where('users_id', $users_id)->where('password', bcrypt($request->opassword))->update(['password'=>bcrypt($request->npassword)]); if($returnValue >= 1) { $success['message'] = "Password updated successfully.."; return $this->sendResponse($success); } else { $error = "Entered Old password is not valid.."; return $this->sendResponse($error); } from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2yWgLqU via IFTTT

Laravel without database configuration

I am using laravel but, i do not want any database connectivity. i do not need any database to use for my site. if i delete config/database.php still error . Also if i delete DB config from .env still issue. Is there any way to use laravel without any database configuration . [1045] Access denied for user 'forge'@'localhost' and database[] not configured Thanks from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2KLBznW via IFTTT

hasFile() is giving false for array of file object in controller Laravel

In the front end I having a loop with input type file with name as img_logo[$key] (of the loop) like: <input type="file" name="img_logo[$key]" class="dropzone" id="" data-index="" > After submitting the form it goes in the controller, there hasFile() giving true for img_logo but giving false for internal arrays. I am stuck here only why this is happening, where I am getting it wrong. Although you can see the array's element is also a file object but hasFile() giving them false. Please guide me here I am having an array of files with key, value pair as mentioned below: array:4 [▼ "img_logo" => array:2 [▼ 1 => UploadedFile {#462 ▼ -test: false -originalName: "Quotefancy-101003-3840x2160.jpg" -mimeType: "image/jpeg" -error: 0 #hashName: null path: "/tmp" filename: "phpGbtonF" basename: "phpGbtonF" pa...

php artisan optimize NULL.ERROR: Symfony\Component\Debug\Exception\FatalThrowableError: Call to undefined method Illuminate\Foundation\Bootstrap

I am setting up an existing Laravel project for the first time in my life, I am using macOS Catlina version 10.15.2 Mongodb 3.2 Php 7.2 When I am using composer install I am getting the below error: php artisan optimize NULL.ERROR: Symfony\Component\Debug\Exception\FatalThrowableError: Call to undefined method Illuminate\Foundation\Bootstrap\ConfigureLogging::configureHandler() I have gone through multiple links on Stack overflow but no luck , I have deleted vendor folder , and composer.lock multiple times and tried to run composer install but the error is same Can some body help me to solve this issue Below is my composer.json { "name": "laravel/laravel", "description": "The Laravel Framework.", "keywords": ["framework", "laravel"], "license": "MIT", "type": "project", "require": { "php": ">=5.6.4", "laravel/framework": "...

IP of a Outgoing Request from AWS EC2 behind ELB

I have a single EC2 with a EIP behind a ELB. All the incoming requests are hiting the ELB and reaching EC2 webserver, as expected. Now from my PHP application I do a Outgoing Curl request to another server (not in AWS) and check the request IP there, it is showing the ELB IP from Pool. I was expecting it to show the EIP of the EC2. Is there something that I am missing, do I need any specific header in Curl request to see EIP in another server? https://forums.aws.amazon.com/thread.jspa?threadID=125346 this thread someone mentioned following, and i was expecting same. When you receive incoming traffic through the load balancer, the responses will go out the same way. However, traffic that is originating from your instance will not pass through the load balancer. Instead, it is sent directly from the public IP address of your instance out to the Internet. The ELB is not involved in that scenario from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3aQ5ZQi via IFTTT

Laravel Dompdf Show Blank When Display Specific Data

When I use this query: $admin = \App\Admin::all(); It works. But when I use this query: $admin = \App\Admin::where('status', "ACTIVE"); Its shows blank! Even though when I use this query to show data at blade file, it's works! Why? from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/35dySVD via IFTTT

Diffrent width and height images layout question in Laravel with fancybox

صورة
Here is Photo viewer laravel project. it worked well. but I'm having problem about image layout. This below image is my current photo gallery page. As you can see images are not line. looks not good. Becase each uploaded photo size are diffrent width and height so this happens I guess. I'm using Laravel. And this is fancybox. and I'm using this gentleman's source code. https://www.itsolutionstuff.com/post/laravel-5-image-gallery-crud-example-from-scratchexample.html I had been changing below css parameter but I couldn't fix. Could you teach me code to fix situation please? CSS of index.blade.php .gallery { display: inline-block; margin-top: 20px; } .form-image-upload{ background: #e8e8e8 none repeat scroll 0 0; padding: 15px; } Image output of Index.blade.php <div class='list-group gallery'> @if($images->count()) @foreach($images as $image) <div ...

how to remove "public" from url

hi everyone, I want to deploy my Laravel project to production. the "public" not removing in base URL. I have tried this solution: rename server.php to index.php cut .htaccess from /public and paste to root it works but CSS, JS, images not loading. if anyone knows about this problem please share your knowledge. Thanks from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2KGnuI7 via IFTTT

laravel, mysql transaction not working after failed one time

I am performing insertion in 4 tables simultaneously using laravel 5.8. When I Submit incomplete Form it will show me error and after that when submit proper data again it will show database error SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`matrimonial_db`.`personal_details`, CONSTRAINT `personal_details_ibfk_1` FOREIGN KEY (`site_user_id`) REFERENCES `siteuser` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION) (SQL: insert into `personal_details` (`site_user_id`, `updated_at`, `created_at`) values (148, 2020-04-29 05:16:53, 2020-04-29 05:16:53)) First time when i fill form it insert data successfully in all tables but when try again it will show me the error. here is a code try { $connection = DB::connection('mysql'); $connection->beginTransaction(); $userData = session()->get('registeruser_data'); $userData->user_type = 'v...

Eliminar archivo en el proyecto despues de eliminarlo en la base de datos

Quiero eliminar un archivo de la base de datos y cuando presiono el botón Eliminar, se eliminan todos los datos de la base de datos, pero la imagen permanece en la carpeta de carga. Entonces, ¿cómo hago esto para trabajar? Gracias Asi es como agrego los archivos a la base de datos y se almacenan en el storage del proyecto: if($request->hasFile('file')) { $file = time().'.'.$request->file->extension(); $request->file->move(storage_path('app/public/pdf'), $file); $history->file = "pdf/".$file; } Uso laravel 6 from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2yRY4Vo via IFTTT

Laravel - Input Autocomplete Outside

My options Input autocomplete are out from my input. Laravel: 5.5 Controller: $(document).on('focus','.autocomplete_txt_APO',function(){ type = $(this).data('type'); autoType='db_artic'; $(this).autocomplete({ minLength: 0, source: function( request, response ) { $.ajax({ url: "", dataType: "json", data: { term : request.term, type : type, }, success: function(data) { var array = $.map(data, function (item) { return { label: item[autoType], value: item[autoType], data : item } }); response(array) } }); }, select: function( event, ui ) { var data = ui.item.data; id_arr = $(this).attr('id'); id = id_arr.split("_"); elementId = id[id.length-1]; $('#inp_artic_'+elementId).val(data.db_artic); $('#inp_vrund_'+elementId).val(data.db_vrund); $('#inp_idmat_'+elementId).val(data.db_idmat); } }); }); <table class="table table-bordered"> <tr> <th class="text-center...

Saving relationships data in model

This is my store function, Laravel 5.5 Here firstly I am saving address first then account, after that I can attach account id to address id. But if there is an error saving account data address data will be created but account is not, Account has one to one relationship with address, Is there any way to save if there is an error on saving account data address gets deleted or it does not save at all, Thank you. public function store(Request $request){ $address_save = false; $account_save = false; ///////After Validation////// $address = new Address; $address->shipping_address1 = $request->shipping_address1; $address->shipping_address2 = $request->shipping_address2; $address->area_id = $request->area_id; $address->city_id = $request->city_id; $address->shipping_state = $request->shipping_state; $address->shipping_pincode = $request->shipping_pincode; $address->shipping_country = $request->shippi...

Laravel count Support Tickets from a user [closed]

I have this in the Dashboard Screenshot of the Dashboard I want that it shows how many Tickets are open / closed / all How do I do this with this Database? Screenshot from SELECT * FROM tickets How do I do this that every user see his own open / closed and all tickets? from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3bMsRS3 via IFTTT

Get the latest row each group based on max date

I am trying to select single from every group where date is max. I am trying to do with this bellow |NO | effective | price | level_one| level_two +---+-------------+----------+|+++++++++++|++++++++++++ |1 | 2011-12-01 | 34 | 1 | 2 |2 | 2011-16-01 | 34 | 1 | 2 |3 | 2011-18-01 | 3434 | 1 | 2 |4 | 2011-16-01 | 3554 | 1 | 3 Result should be |NO | effective | price | level_one| level_two +---+-------------+----------+|+++++++++++|++++++++++++ |3 | 2011-18-01 | 3434 | 1 | 2 |4 | 2011-16-01 | 3554 | 1 | 3 But result come |NO | effective | price | level_one| level_two +---+-------------+----------+|+++++++++++|++++++++++++ |3 | 2011-12-01 | 34 | 1 | 2 |4 | 2011-16-01 | 3554 | 1 | 3 tried with $price = App\Price::with('others') ->orderBy('effective', 'Desc') ->groupBy('level_one',...

how i can count different different multiple same category according to date in laravel

This is my query i want to get sperate count of same category id DB::table('form_categories') ->rightjoin('form_submissions','form_categories.id','=','form_submissions.category_id') ->where('form_submissions.user_id' , Auth::user()->id) ->where('form_submissions.created_at', '>', Carbon::now()->startOfWeek()) ->where('form_submissions.created_at', '<', Carbon::now()->endOfWeek()) ->groupBy('date') ->orderBy('date', 'DESC') ->get(array( DB::raw('Date(form_submissions.created_at) as date'), DB::raw('COUNT(form_submissions.category_id) as "category"'), )); from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2W7i12A via IFTTT

error 403 forbidden, when I upload image in laravel 5.8

صورة
I testing a code for upload image on laravel 5.8 local and I uploaded image unsuccessful then I recieved error 403 forbidden. public function store(Request $request) { request()->validate([ 'profile_image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); if ($files = $request->file('profile_image')) { // Define upload path $destinationPath = public_path('/profile_images/'); // upload path // Upload Orginal Image $profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension(); $files->move($destinationPath, $profileImage); $insert['image'] = "$profileImage"; // Save In Database $imagemodel= new Photo(); $imagemodel->photo_name="$profileImage"; $imagemodel->save(); } return back()->with('success...

Merge existing excel files into one excel file Laravel

The problem is very simple but I can't find a solution anywhere. I need to combine a few excel files in the storage directory into 1 excel file where every excel file is now a sheet in the new excel file. I have been experimenting with Maatwebsite/Laravel-Excel (version 3.1) but without success... Someone an idea how to tackle this problem? from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2SbhD1B via IFTTT

record specific data to table with 30minute time interval using laravel

I created two tables,which are rainfall and status_msgs.i want to put record to rainfall table from status_msgs table.now i created a code which can give 10 records of specific UNIT_ID.(UNIT_ID is column of my status_msgs table)UNIT_ ID is A01.now i want that A01 data's record to rainfall table with 30minute time interval.i get data to a variable shown below.and i creadted a model called Statusmsg. $datas = Statusmsg::where('UNIT_ID', '=', 'A01')->take(10)->get(); foreach ($datas as $data) { } from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2SfWbIZ via IFTTT

Laravel SweetAlert not working inside validation fails block

I am using realrashid/sweet-alert version 3.1 with laravel 5.8 the issue is when I am using alert after form success or after validation failed its not working here is my code public function store(Request $request) { $rules = [ 'title' => 'required', 'title_desc' => 'required', 'desc' => 'required', 'pic' => 'required', ]; $customMessages = [ 'title_desc.required' => 'The Short Description field is required.', ]; $validator = Validator::make($request->all(), $rules, $customMessages); if ($validator->fails()) { Alert::error('error', 'Validation Errors'); return back(); } $update_arr = array( 'title' => "hello", 'description' => "world", 'title_desc...

How to replace/convert double slash to single slash in filesystem laravel 5.8

صورة
I want to store excel file to local disk in my server, and do with filesystem in laravel 5.8. This is my filesystem config. 'trading' => [ 'driver' => 'local', 'root' => 'C:\Users\Administrator\Documents\SPOP\tradingid', ] And for do store the excel file, i'm using maatwebsite package like this public function generate(Request $request){ $now = date("Y-m-d"); $id_trans = Transaction::whereIn('id', $request->ids)->pluck('transaction_id'); $data = Excel::store(new ExportData($id_trans), 'ExcelFile'.$now.'xlsx', 'trading'); if ($data) { return response()->json(['status' => 'success', 'message' => 'Success To Generate']); } else { return response()->json(['status' => 'error', 'message' => 'Failed To Generate']); } } When the function executed, i got error m...

How to switch destination mail address by selecting check box in Laravel contact form

This is conctact form and sorking. I would like to switch email destination by User selecting check box. For example. Here is a coulumn called 'genders'. When User check 'man' select box, Email destination will be [TO]'man_survey@12345677.site' and [CC] is 'man_cc_survey@12345677.site'. When User check 'female' ,Email destination will be [TO] 'female_survey@12345677.site' and [CC] is 'female_cc_survey@12345677.site' Could you teach me how to add this function to my current code? my Laravel Framework is 5.7.28 <?php namespace App\Http\Controllers; use App\Http\Requests\ContactRequest; use App\Http\Controllers\Controller; use App\Contact; class ContactsController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $types = Contact::$types; $genders = Contact::$genders; return view('contacts.inde...

Create New Passport Client for a User in Laravel and Passport inside Controller

Is there a way to create passport client in Laravel. For example, to create a Token, we can do: $user = $request->user(); $token = $user->createToken("myApp")->accessToken; Do we something for Client too? $user = $request->user(); $token = $user->createClient("myApp")->accessClient; I checked the documentation and it is possible to create a client using an API, but the example is in Vue.JS const data = { name: 'Client Name', redirect: 'http://example.com/callback' }; axios.post('/oauth/clients', data) .then(response => { console.log(response.data); }) .catch (response => { // List errors on response... }); But I am unable to run this example in POSTMAN... I am not sure which function or method is being triggered for above API Call. How can I make use of this POST method outside VueJS. from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3eVfQYv via IFTTT

How do we Clear Controller And Model cache in Laravel

I have very simple application in Laravel 5.5. My Route : Route::resource('books', 'BookController'); My Controller is app/http/Controllers/BookController.php My Model is app/Book.php I have similar other modules as well. INTERESTING PART IS : My Book controller changes are not being reflected in browser. I thought of clearing the cache so cleared all caches. 1. Cleared Application Cache > php artisan cache:clear 2. Cleared Route Cache > php artisan route:clear 3. Cleared Configuration Cache > php artisan config:clear 4. Cleared Compiled Views Cache > php artisan view:clear I was not sure which cache was causing the issue so I cleared all. Still my changes are not being reflected in the browser, but when I change the view files, the changes are being reflected. Any Suggestion please????? from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3aO3Pks via IFTTT

Laravel 7 Pagination and Bootstrap Tabs

I've been struggling with this issue for days now. Basically I use Laravel 7 and Bootstrap tabs called 'All Products' and 'Special Products'. The problem is: I want to paginate the results, but it doesn't work quite as expected. For example, the initial active tab is 'All Products', if i click page 3 on that tab and switch to 'Special Products' tab, it loads page 3 of that tab as well instead of page 1. I hope this makes sense? My controller file: public function index() { $products = Product::with('brands')->paginate(1,['*'],'products'); $specials = Product::where([ ['discount', '!=', null], ['discount', '!=', '0'] ])->paginate(1,['*'],'specials '); return view('products.index', ['products' => $products, 'specials ' => $specials ]); } My view file: <div class="...

Unable to get input data from Form submit GET request in laravel 5.1

I have a search form that is sending a GET request to the method that it is using to view the form: <form class="form-horizontal" method="GET" action=""> <div class="form-group form-group-sm"> <div class="col-sm-3"> <input type="text" name="inputdate" class="form-control datepicker" placeholder="Date" > </div> <div class="col-sm-2"> <button class="btn btn-primary btn-sm btn-block" type="submit"> <i class="fa fa-search" aria-hidden="true"></i> Search </button> </div> </div> ...

Laravel - Count of items through with belongs to

A company can have many delivery dates. A delivery date may have many entries. The Entry model contains public function company() { return $this->belongsTo(Company::class); } public function delivery_date() { return $this->belongsTo(MgDeliveryDate::class, 'mg_delivery_date_id'); } What I want is a count of how many entries each delivery date has for each company. For example, something like $companies = Company->with('delivery_dates', 'delivery_dates.entries')->withCount('delivery_dates.entries') So if my data was Company Delivery Date Entry Number A 1/2/2020 1 A 1/2/2020 2 A 2/2/2020 3 B 1/2/2020 4 I would get two companies, company A with two delivery dates and a count of 2 for the first date(1/2/2020) and 1 for the second date(2/2/2020) and company B with one delivery d...

How to fix Laravel api update not working?

I want to update a review by ID using the following link in Postman http://localhost:8000/api/v1/reviews/2 I have the following in the ReviewController public function update(Request $request,Product $product, Review $review) { $review->update($request->all()); // $review->save(); return response([ 'data' => new ReviewResource($review) ],Response::HTTP_CREATED); } When trying to update content for null fields for booktitle and description using PUT method I get a success message however the record remains the same. It is not updated. This is the review model file <?php namespace App\Model; use App\Model\Product; use Illuminate\Database\Eloquent\Model; class Review extends Model { public $timestamps = true; protected $fillable = [ 'booktitle', 'description', 'updated_at', 'created_at', ]; from Newest questions tagged laravel-5 - Stack Overflow ...

Laravel validators: prevent submit 2 parameters together

How to prevent presents of 2 parameters that existed in required_without_all validator, ex: return [ 'user' => 'required_without_all:customer,public', 'customer' => 'required_without_all:user,public', 'public' => 'required_without_all:user,customer', ]; How to prevent user from submit 2 keys from above together, ex: http://127.0.0.1:8000/app/groups-statistics?user=10&customer=10 These are allowed requests: http://127.0.0.1:8000/app/groups-statistics?user=10 http://127.0.0.1:8000/app/groups-statistics?customer=10 http://127.0.0.1:8000/app/groups-statistics?public=true Disallowed: http://127.0.0.1:8000/app/groups-statistics?pubilc=true&customer=10 http://127.0.0.1:8000/app/groups-statistics?user=10&customer=10 http://127.0.0.1:8000/app/groups-statistics?public=10&customer=10 from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3aIs57e via IFTTT

Store array inside of array in db using laravel

صورة
I have a common array from request named complemntartData[]. from that array i get some values.i need to store these data in db table field.i used implode function but it shows array to string conversion. if($request->input('complementaryData')){ foreach($request->input('complementaryData') as $name => $value){ $data = explode ("_", $name); $A = []; $B = []; if($data[0]=="TextField"){ $B["id"] = $data[1]; $A["TextField"] = &$B; $B["data"] = $value; } if($data[0]=="Archive"){ $B["id"] = $data[1]; $A["Archive"] = &$B; $B["data"] = $value; } if($data[0]=="MultipleChoice"){ $B["id"] = $data[1]; $A["MultipleChoice"] = &$B; $B...

Setting active class for menu items dynamically in laravel

I'm creating a laravel application using bootstrap 4. I have my main navigation menu in app.blade.php . And I have four main blades, About,Product,Contact and Blog. Then I needed to change the menu item active class according to the current page. As the menu being loaded dynamically from the app.blade.php I had to set the active class for current page in the navigation menu dynamically. What I did was in every blade I've defined a variable called, $currentpage and assign page name in to it, assume it's blog.blade.php <?php $currentPage = 'blog';?> @extends('layouts.app') @section('content') and in the app.blade.php , <li class="<?php if($currentPage =='blog'){echo 'nav-item active';}?>"> <a class="nav-link " href=""></a> </li> So this works properly.. but I want to know Is this the correct way of doing it and what a...

Laravel multi language option

Currenly i am working a mlm website. Client requirement is When user come to website they can select language. when the click specific language then it will automatically translate language <li> <img class="language-flag" src="/icon/flags/English-flag.svg" alt=""> <a href="" title="English" class="language__item" style="background-position:-0px -0px;" data-cf-modified-6443d1b43f4ab48f9fb6cc28-="" data-cf-modified-107c802c5212d7df077f3a9f-="">English</a> </li> <li> <img class="language-flag" src="/icon/flags/Arabic-flag.svg" alt=""> <a href="#" title="Arabic" class="language__item" style="background-position:-100px -0px;" data-c...

How to preserve angular routes when using laravel?

I am new to Laravel, so take it easy on me :) I have had my Angular 7 application on www.somedomain.com for a year now, but I am at the point of needing a backend framework. The hosting company fully supports Laravel 5.*; therefore, I installed it on the server. I have made Laravel's default route to point to Angular's index.html like so Route::get('/', function () { View::addExtension('html', 'php'); return View::make('index'); }); Now the webpage opens my Angular app successfully, but routes are not the same as they used to. I manage GUI pages via Angular routes and try to use Laravel routes for Http requests. My problem is that now www.somedomain.com/about view can be accessed from the Angular app by pressing the navigation button, and in the URL it shows https://ift.tt/2SaanmQ correctly. But when I try to directly access that URL, it shows 500 server error because it is being handled by Laravel. How can I make sure my GUI routes wo...

How to use get and paginate same time in Laravel

I would like to use paginate. I researched if I use paginate() I have to erase ->get(). but I got error. Could you teach me how to add paginate please? my current code $images = ImageGallery::orderBy(DB::raw('LENGTH(wc), wc'))->get()->paginate(5); return view('image-gallery2',compact('images')); blade file code UPDATE if I do this $images = ImageGallery::orderBy(DB::raw('LENGTH(wc), wc'))->get()->paginate(5); This error BadMethodCallException Method Illuminate\Database\Eloquent\Collection::paginate does not exist. If I write below $images = ImageGallery::orderBy(DB::raw('LENGTH(wc), wc'))->paginate(5); return view('image-gallery2',compact('images')); I got this error Facade\Ignition\Exceptions\ViewException Call to undefined method App\ImageGallery::links() (View: //resources/views/image-gallery2.blade.php) from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2SavqWf via IFTTT

how to pass multiple parameters through route using Laravel collective Forms & HTML Addins?

lets assume we have a Delete button inside a form : {!! Form::open(['route' => ['posts.destroy','id'=>$post->id], 'method' => 'delete']) !!} {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!} {!! Form::close() !!} i need to pass two or more variables through the Form Route like this: {!! Form::open(['route' => ['posts.destroy','id'=>$post->id,'title'=>$post->title], 'method' => 'delete']) !!} {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!} {!! Form::close() !!} I try to different ways , to take these two parameters but still I couldn't retrieve data ErrorException in PostController.php line 99: Missing argument 2 for App\Http\Controllers\PostController::destroy() from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2VWKeJn via IFTTT

Ambiguous column name laravel 5.6+

صورة
i have a problem with error called "Column 'id' in field list is ambiguous". I've tried to fix it by using aliases on columns but i had no luck in fixing it. Query looks like this: SELECT `id` AS `pf_id`, `id_feature` AS `pf_if`, `id_feature_value` AS `pf_ifv`, `product_features`.`id_product` FROM `features` INNER JOIN `product_features` ON `product_features`.`id_feature` = `features`.`pf_id` WHERE `product_features`.`id_product` IN ( 33003, 33004, 33011, 33012, 33013, 33015, 33016, 33017, 33018, 33019, 33020, 33021, 33022, 33023, 33024, 33025, 33026, 33029, 33030, 33032 ) AND `id_feature` = 5 Id is used only in select and inner join. It's calling product_features table and features table. Only this pice of code is not working - any other relation on product is working fine. Below are additional info about table structure plus relation:...

Larave 5.2 Session not saving other data

I have a part of my code that saves data in the session and will retrieve my data on the same controller file but cannot access it. Here's how I do it: public function index(Request $request) { //some process \Session::put('data', [ 'recruits' => $recruits, 'header' => $header, 'condition' => $condition, 'sort' => $sort, ]); //so when I retrieve it here thru dd(\Session::get('data')), it displays well. return redirect()->route('admin.filter'); } //this is the function which is in the same file public function filter() { dd(\Session::get('data')); // data displayed in my session is only recruits and condition } Anyone has idea on this? from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2Kz9SOX via IFTTT

How to get text Strings order in Laravel project

I would like to sort column like orderBy. 'WC' columns has such data 'AB-1' 'AB-2' 'AB-5' 'AB-300' 'AB-1980' .... etc Front of "AB-" letter is same. then comes number. Could you teach me how to write code please? public function index() { $images = ImageGallery::orderBy('wc', 'asc')->get(); return view('image-gallery',compact('images')); } from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2SaedfF via IFTTT

How to give order query when using scorp

I'm trying to get image data. giving order by id desc. I add orderBy sentece after get() it didn't work. Could you teach me how to add order query when using :: scope? public function index() { $images = ImageGallery::get()->orderBy('id', 'desc'); return view('image-gallery',compact('images')); } from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2Kw2ZxY via IFTTT

Laravel dynamic routing for search

I would like to generate dynamic route when user clicks on Search button. I know it can be done with following GET method https://laravel.dev/search?q=parameter https://laravel.dev/search?state=XYZ&category=Automobile But instead I would like to do following https://laravel.dev/search/state/XYZ/category/Automobile So if I add an extra parameter in search form it will just add onto the URL. The parameters may be optional so can not add a fix route in routes . User may supply state or search through all states. https://laravel.dev/search/category/Automobile How can I achieve that? Thank you from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3bFvWU2 via IFTTT

How to return an OUT/INOUT parameter using Laravel + PostgreSQL?

I am using PostgreSQL and Laravel 5 and I could find any resource explaining how to recover the output parameters from DB::statement call of a procedure in PostgreSQL. I saw people setting cursors.. but is that the only way? Is that so hard? from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3cO1aZ8 via IFTTT

How to update many db setting values in laravel

1.I have checkboxes data from view. $data =["name1" =>"value1","name2"=>"value2","name3"=>"value3"] 2.I need to update in controller something like: Config::update( ['id'=>1,"name"=>"name1","value"=>"value1"], ['id'=>2,"name"=>"name2","value"=>"value2"], ['id'=>3,"name"=>"name2","value"=>"value3"], ); from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2xNcXbz via IFTTT

How to pass optional ID to Laravel Controller from Route?

I want to pass an ID to my controller from Routes: Route::get('user/{id?}', function ($id= null) { return $id; }); However, I'm not sure where to put the controller name and function? MyController@get Laravel's documentation and other questions don't seem to be related to this issue. What am I missing here? from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/354obVb via IFTTT

laravel foreach and if else loop errors both in count and variables something

code of 1st error : @extends('layouts.app') @section('content') <h1> posts</h1> @if(count($posts)>1) @foreach($posts as $post) <div class="well"> <h3></h3> </div> @endforeach @else <p> no posts found</p> @endif @endsection and image also attached . [enter image description here][1] after i follow the instructions of the chrome this occurs and code will be .. even i have removed the @ and try if() like this .. code 2 ; @extends('layouts.app') @section('content') <h1> posts</h1> @if(count($posts ?? '')>1) @foreach($posts ?? '' as $post) <div class="well"> <h3></h3> </div> @endforeach @else <p> no posts found</p> @endif @endsection enter image description here [1]: https://i.stack.im enter code here gur.com/21weC.png from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2VzG5vP via IFTTT

Slow photo loading in Laravel

صورة
I have Laravel code below in my project on local machine and running it on development mode. Photos are stored in public folder. In current example I have 17 photos in mobile_photos folder, the weight of all of them is 572kB. The problem is slow loading of mentioned images even they are not heavy, exact time you can find on photo below. I expected to load these ptohos in ms but as you can see loading time for one photo is more then more then 1s. Any idea how to fix this problem? <link rel="stylesheet" href="/css/justifiedGallery.css" /> <script type="text/javascript" src="/js/jquery.min.js"></script> <script type="text/javascript" src="/js/jquery.justifiedGallery.js"></script> <div id="basicExample" class="justified-gallery"> @foreach ($photo as $photo) <a href=""> <img alt="caption for image...

Getting Token expired for all json post requests

صورة
I am passing token in all the headers but it only works for login, after that for all requests it says "Token Expired" Token Setup : Output in Result tree : Also when I look at my website, I can see 2 tokens : <!-- CSRF Token --> <meta name="csrf-token" content="AqrfjMcG1adWWDlx8YYkYqOCy3Mwp7fRynwut222"> <input type="hidden" name="_token" value="AqrfjMcG1adWWDlx8YYkYqOCy3Mwp7fRynwut222"> So I am passing _token for all request headers as above both has same content/value. I am also not sure about x-socket-id , It came be default as I recorded script. is it ok to remove it? from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2S3iVf1 via IFTTT

Send CSV file as Email attachement in Laravel

I am working on Laravel file attachment. I have successfully generated a .pdf file and sent as attachment in mail. Now I have to send CSV file as attachment in mail with Laravel. When I click the submit button it just download the file rather then to send an email. Controller Code: $data["email"] = $request->recipient_email; $data["subject"] = 'Cashup Report for '. $venue->name; $data["bodyMessage"] = $venue->name.' from '.$start.' to '.$end ; $excel = Excel::create(uniqid().'Cashups', function($excel) use($transactions,$start,$end,$venue) { $excel->sheet('New sheet', function($sheet) use($transactions,$start,$end,$venue) { $sheet->loadView('excel.cashups', array('transactions' => $transactions, 'start'=> $start, 'end' => $end, 'venue' => $venue)); }); }); //Feedback mail to client Mail::send('emai...

is there anyway to remove laravel telescope database without running another migration?

I have completely removed this package from my project but the databases still there, is another way to remove them too? from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2Y5i01M via IFTTT

Property [categories] does not exist on this collection instance. (View: D:\xampp\htdocs\olshop\resources\views\backend\product\index.blade.php)

this is my Model //relation from model products to model categorys public function categorys() { return $this->belongsTo('App\Category'); } //relation from model products to model categorys public function categorys() { return $this->belongsTo('App\Category'); } this is my controller public function index() { //controller buat manggil foreachnya $data['title'] ='Product'; $data['page'] = 'Semua Product'; $data['products'] = Product::all(); return view('backend.product.index', $data); } **this is my ** @foreach($products->categorys as $key => $value) <tr> <!-- view bladenya --> <td></td> <td></td> <td></td> I am trying to using $products->$categorys but its gone wrong from Newest questions tagged laravel-5 - Stack Overflo...

Firebase receive notification while tab is active or on focus

What i want is to be able to perform an action when a user receives a notification while the browser is open and tab is active or focused. I can seem to figure out a way to receive notification or perform am action while browser tab is open or focused, It works well when browser is at the background.I upgraded to firebase version 7.8.0 and below is the code am using <script> // Your web app's Firebase configuration var firebaseConfig = { apiKey: "xxxx", authDomain: "xxx", databaseURL: "xxxxx", projectId: "xxxx", storageBucket: "xxx", messagingSenderId: "xxx", appId: "xxx" }; // Initialize Firebase if (!("Notification" in window)) { console.error("Notification isn't enabled"); } else if (Notification.permission === "granted") { console.log("Notification is enabled"); } else if (Notification.permission !== "denied") {...

If output of \Log::info depens on some options?

If output of \Log::info('text'); function is dependable on some options ? in .env I have : APP_DEBUG=false and in config/app.php 'debug' => env('APP_DEBUG', false), Also in config/logging.php I have options(seems default): <?php use Monolog\Handler\StreamHandler; use Monolog\Handler\SyslogUdpHandler; return [ 'channels' => [ 'stack' => [ 'driver' => 'stack', 'channels' => ['daily'], ], 'single' => [ 'driver' => 'single', 'path' => storage_path('logs/laravel.log'), 'level' => 'debug', ], 'daily' => [ 'driver' => 'daily', 'path' => storage_path('logs/laravel.log'), 'level' => 'debug', 'days' => 14, ...