Archive d’étiquettes pour : Laravel


What Is File Validation in Laravel?

Laravel validation is a way to perform a validation role. We can check the file type, file size, etc. File validation is typically used to avoid unwanted file uploads in a server or application.

Today, we will learn about file upload and storing in Laravel 9.

Project requirements are provided below:

  • MySQL 8.0+
  • MariaDB 10.2+
  • PHP 8.1

Here is an example of defining the FileUpload:

  1. Process 1. Create a FileUpload Project
  2. Process 2. FileUpload Project Database Connection
  3. Process 3. Create a Model and Controller in the FileUpload Project
  4. Process 4. Run and Test the FileUpload Project

Process 1. Create a FileUpload Project

Step 1 is to run this command line to install Laravel 9 on our server or pc. For that, we need to open the Windows SSH terminal in the folder.

Composer createproject Laravel/Laravel FileUpload

Process 2. FileUpload Project Database Connection

Open the .env file on the FileUpload project and add a new database name, username, and password.

Here is the following code:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE= FileUpload Database name
DB_USERNAME= FileUpload Database user name
DB_PASSWORD= FileUpload Database password

Process 3. Create a Model and Controller in the FileUpload Project

Merienda the database is connected, we must create a model and controller for the FileUpload Project.

For that, we need to run the following command:

php artisan make:model FileUpload mc

Now, go to “databasemigrations2022_07_11_074014_create_file_uploads_table.php” file. This name could be different on your side. Now, we need to put these two lines in the file:

$table>string(‘file_name’)>nullable();
$table>string(‘file_path_location’)>nullable();

Its looks like this

return new class extends Migration
{
   
    public function up()
    {
        Schema::create(‘file_uploads’, function (Blueprint $table) {
            $table->id();
            $table->string(‘file_name’)->nullable();
            $table->string(‘file_path_location’)->nullable();
            $table->timestamps();
        });
    }

   
    public function down()
    {
        Schema::dropIfExists(‘file_uploads’);
    }
};

We modify our FileUpload model in “appModelsFileUpload.php”. We add fillable property there. The code is shown below:

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class FileUpload extends Model
{
    use HasFactory;
    protected $fillable = [
        ‘file_name’,
        ‘file_path_location’
    ];
}

Now, we need to migrate the table to the database to run this command:

Merienda migration is completed, we need to create two functions. One function is for going to the upload page, and another is to upload a file in the directory and store it in the database.

Go to the “appHttpControllersFileUploadController.php” file:

Now, add this code to the controller:

 public function fileview(Request $request)
    {
        return view(‘file-upload’);
    }

And another function is shown below:

 public function uploadTheFile(Request $request)
    {

            $rules = array(
                ‘attachment’ => ‘mimes:jpeg,png,jpg,gif,svg,pdf|max:1000’,
            );
            $messages = array(
                ‘attachment’ => ‘ Image need Less then 1Mb.’,
            );

            $validator = Validator::make($request->all(), $rules, $messages);
            if ($validator->fails()) {
                return redirect()->route(‘fileviews’)->with(‘success’, ‘Successfully Added’);
                return redirect()->route(‘fileviews’)->withErrors($validator);
            }else{
                $imageName = time() . ‘.’ . $request->attachment->extension();
                //remove image before upload

               $path = $request->attachment->move(public_path(‘storage/attachment/’), $imageName);
               $departmentname[‘file_name’] = $imageName;
                $departmentname[‘file_path_location’] = $path;
                FileUpload::create($departmentname);
                return redirect()->route(‘fileviews’)->with(‘error’, ‘No file added’);
            }

    }

In the uploadTheFile function, we used the Validator.

We created this function to upload the view. Thus, we need to create the view in the Laravel view located in “resourcesviewsfile-upload.blade.php”.

Let’s build the view for uploading the file.

Copy the code and paste it into the view.

<!DOCTYPE html>
<html lang=«en»>

<head>
    <meta charset=«utf-8» />
    <meta name=«csrf-token» content=«{{ csrf_token() }}»>
    <meta name=«viewport» content=«width=device-width, initial-scale=1.0»>
    <!– CSS only –>
    <link href=«https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css» rel=«stylesheet»
        integrity=«sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBl6DOitfPri4tjfHxaWutUpFmBp4vmVor» crossorigin=«anonymous»>
    <!– JavaScript Bundle with Popper –>
    <script src=«https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js»
        integrity=«sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2» crossorigin=«anonymous»>
    </script>
</head>

<body>
    <div clas=«container»>
        <div class=«col-lg-12»>

            <div class=«card-box»>
                <div>
                    Message
                    @if ($errors->any())
                    @foreach ($errors->all() as $error)
                    <div>{{$error}}</div>
                    @endforeach
                    @endif
                </div>

            </div>
        </div>

        <div class=«col-lg-12»>
            <div class=«card-box»>
                <form action=«{{ route(‘uploadTheFile’) }}» method=«POST» enctype=«multipart/form-data»>
                    @csrf
                    <div class=«form-group»>
                        <label for=«name»>Upload FIle</label>
                        <input type=«file» class=«form-control» name=«attachment» required>
                    </div>

                    <div class=«text-right»>
                        <button type=«submit» class=«btn btn-success waves-effect waves-light»>Save</button>

                    </div>
                </form>
            </div>
        </div>
    </div>

</html>

Now, we need to create two routes for uploading files in our project:

Route::get(‘/file-view’, [FileUploadController::class, ‘fileview’])->name(‘fileviews’);
Route::post(‘/file-upload’, [FileUploadController::class, ‘uploadTheFile’])->name(‘uploadTheFile’);

Merienda the route is created, go to the “/file-view” and it should look like the following image in the browser:

Process 4. Run and Test the FileUpload Project

Now, we need to run the command and check file upload if it is working or not:

We need to check whether the code is working or not through the route for checking.

Select a file and try to upload it. In my case, it worked fine.

Merienda a file is uploaded, it can be found in the following:

Image is here

Also, it is inserted into the Database.

Conclusion

In this article, we created this Laravel FileUpload project with Laravel 9. Creating a data table in Laravel using FileUpload is very useful to call the file again. We hope this FileUpload project example will help you to understand the file Upload in Laravel 9.



Source link


Laravel 9 log is an integral part of the Laravel 9 application. Basically, it is used as an application for monitoring the application activity. Laravel 9 has robust log services for converting log messages into a file. Today, we will demonstrate Laravel 9 logging. This tutorial helps you to understand your application status. What’s going on with your application. If there were an error in your software, you would see the system error message in your log file. Laravel 9 has a default logging that is based on the Laravel channel.

How It Works

Laravel 9 allows developers to log messages about the system behavior of any application to files, such as the system of error logs, and send them to notify the development teams.

It is based on the Laravel 9 channels. Channels are a specific way of writing a system’s log message. Every channel represents a different destination, and we can send messages to different channels simultaneously.

  1. Process One: Install Laravel 9 in the System
  2. Process Two: Configure Log in Project
  3. Process Three: Run and Test the System

Process One: Install Laravel 9 in the System

We have to run the following command to install our log project:

composer createproject laravel/laravellogProject

It should look like the following image:

Then go to the project root directory and open the logging project.

Process Two: Configure Log in Project

All the project configuration options are located in your application config folder. Now, go to the logging.php file located in the config folder. The logging.php file allows developers to configure logging channels by adding, updating, or deleting.

By default, it should look like the following image:

The stack channel is selected by default. The channels look like the following image in the logging file:

    ‘channels’ => [
        ‘stack’ => [
          => ‘stack’,
            ‘channels’ => [‘single’],
            ‘ignore_exceptions’ => false,
        ],

        ‘single’ => [
            ‘driver’ => ‘single’,
            ‘path’ =>storage_path(‘logs/laravel.log’),
            ‘level’ =>env(‘LOG_LEVEL’, ‘debug’),
        ],

        ‘daily’ => [
            ‘driver’ => ‘daily’,
            ‘path’ =>storage_path(‘logs/laravel.log’),
            ‘level’ =>env(‘LOG_LEVEL’, ‘debug’),
            ‘days’ => 14,
        ],

        ‘slack’ => [
            ‘driver’ => ‘slack’,
            ‘url’ => env(‘LOG_SLACK_WEBHOOK_URL’),
            ‘username’ => ‘Laravel Log’,
            ‘emoji’ =>‘:boom:’,
            ‘level’ =>env(‘LOG_LEVEL’, ‘critical’),
        ],

        ‘papertrail’ => [
            ‘driver’ => ‘monolog’,
            ‘level’ =>env(‘LOG_LEVEL’, ‘debug’),
            ‘handler’ =>env(‘LOG_PAPERTRAIL_HANDLER’, SyslogUdpHandler::class),
            ‘handler_with’ => [
                ‘host’ => env(‘PAPERTRAIL_URL’),
                ‘port’ => env(‘PAPERTRAIL_PORT’),
                ‘connectionString’ => ‘tls://’.env(‘PAPERTRAIL_URL’).‘:’.env(‘PAPERTRAIL_PORT’),
            ],
        ],

        ‘stderr’ => [
            ‘driver’ => ‘monolog’,
            ‘level’ =>env(‘LOG_LEVEL’, ‘debug’),
            ‘handler’ =>StreamHandler::class,
            ‘formatter’ => env(‘LOG_STDERR_FORMATTER’),
            ‘with’ => [
                ‘stream’ => ‘php://stderr’,
            ],
        ],

        ‘syslog’ => [
            ‘driver’ => ‘syslog’,
            ‘level’ =>env(‘LOG_LEVEL’, ‘debug’),
        ],

        ‘errorlog’ => [
            ‘driver’ => ‘errorlog’,
            ‘level’ =>env(‘LOG_LEVEL’, ‘debug’),
        ],

        ‘null’ => [
            ‘driver’ => ‘monolog’,
            ‘handler’ =>NullHandler::class,
        ],

        ‘emergency’ => [
            ‘path’ =>storage_path(‘logs/laravel.log’),
        ],
    ],

A driver regulated the channels. The driver will set what log data will be recorded into the system log file. There are lots of drivers built-in Laravel 9. You have to check Laravel 9 driver documentation for the driver list.

Now, write a log message in the Laravel application. We can pass a log message throw log data.

For that, we have to create a controller named “Logmessage”. Now, we need to run this command:

php artisan make:controllerLogmessage

After being created, it should look like this:

Now, we need to create a function in the controller:

class Logmessage extends Controller
{
    public function logtest()
    {

Log::info(» Here is dummy log data»);
        return view(‘welcome’);
    }
}

We use log::info to see the logmessage.

Process Three: Run and Test the System

Now, run and test the logging project.

We need to create a route for checking.

Next, we need to run the project and use the following command:

Then, go to the route and log in to your application.

Before loading the URL, you can check under the storage directory.

There is no log file.

Merienda you load the URL, it will show the log file.

The URL will look like the following image:

Then, load the URL:

The Laravel.log file was created, and we will open the following log file:

Here, you can check all your application errors.

Conclusion

In this article, we discussed how Laravel logging was accomplished in three processes. The processes included installing Laravel 9 in the system, configuring log in the project, and running and testing the system. We hope this article will help you with your application activity.



Source link


Laravel 9 has an excellent feature named Eloquent. It is an ORM (object-relational mapping), and it helps users to communicate between applications to databases very easily. In Laravel 9, when we use Eloquent, it works as a “Model” and communicates with the database. It helps you get data from the table in the database.

In Laravel 9, there are multiple ways to get data by order. One way is shown below:

Today, we will learn how to use orderBy in Laravel and when to use it.

orderBy in Laravel

In Laravel 9, when we need to sort our data collection by descending or ascending order from the database. Then we need to use an orderBy in the Laravel query. In the regular MySQL queries, we use it as shown below:

Select * from ‘collection’ where ‘status’ = ‘something’ order by ‘collection_id asc

But, Laravel has a different way of assigning the following:

->orderBy(‘collection_id’, ‘asc’)

Project requirements are given below:

  • MySQL 8.0+
  • MariaDB 10.2+
  • PHP 8.1

Here is an example of defining the orderBy query:

  1. Process1. Create an orderBy Project
  2. Process 2. Database Connection
  3. Process 3. Apply the orderBy Method
  4. Process 4. Run and Test the orderBy Project

Process 1. Create an OrderBy Project

Now, we need to run this command to create this project:

Composer createproject Laravel/Laravel orderByProject

Process 2. Database Connection

Open the .env file on the orderByProject project and add new database details.

Here’s the following code:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Database name
DB_USERNAME=Database user name
DB_PASSWORD=Database password

Check the following image:

Process 3. Apply the orderBy Method

Before we apply orderBy to our project, we will need to create a database table for our database. For that, we will create a table called “CollectionList”. We have to run the following command to create the table:

php artisan make:modelCollectionList m

The code is provided below:

return new class extends Migration
{

    public function up()
    {
Schema::create(‘collection_lists’, function (Blueprint $table) {
            $table->id();  //coche increment
            $table->timestamps();
        });
    }

    public function down()
    {
Schema::dropIfExists(‘collection_lists’);
    }
};

I need to add these two to the following code:

$table>string(‘name’)>nullable();
$table>longText(‘details’)>nullable();

Let’s migrate the data to the database. Run the following command:

Next, create a controller to manage the function with the query.

Here, we created a controller named “CollectionList” for our OrderBy project. We need to run this command to create the following project:

php artisan make:controllerCollectionList

The code should look like this:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class CollectionList extends Controller
{
    //
}

Now, I need to create a function in the controller:

The name of the function isallCollection.

After adding this function, it should look as follows:

<?php

namespace AppHttpControllers;

use AppModelsCollectionList as ModelsCollectionList;
use IlluminateHttpRequest;

class CollectionList extends Controller
{
    public function allCollection()
    {
        $alldata = ModelsCollectionList::orderBy(«id», «asc»)->get();

        return view(‘welcome’,compact(‘alldata’));
    }
}

For the get() method, we need to use data in ascending order:

   $alldata = ModelsCollectionList::orderBy(«id», «asc»)>
get();

To get the data in descending order, we need to use the following:

   $alldata = ModelsCollectionList::orderBy(«id», «desc»)>get();

Add a view under the resourceView folder called welcome.blade.php.

<html>

<head>
<meta name=«viewport» content=«width=device-width, initial-scale=1.0»>
<link href=«//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css» rel=«stylesheet» id=«bootstrap-css»>
<script src=«//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js»></script>
<script src=«//code.jquery.com/jquery-1.11.1.min.js»></script>
<!—— Include the above in your HEAD tag ———->

<head>

<div class=«container»>
<div class=«row»>
<div class=«col-md-12 text-right»>

</div>
</div>
            @foreach($alldata as $each_article)
<div class=«col-md-12»>
<h1>{{$each_article->name}}</h1>

<hr>

</div>
            @endforeach
</div>

</html>

Now, we need to add a route in routesweb.php:

Route::get(‘/collection’, [CollectionList::class, ‘allCollection’])->name(‘allCollection’);

Process 4. Run and Test the orderBy Project

Next, we need to run the following:

For the ascending order, the project will look like the following image:

For the descending order, it looks like the following image:

Conclusion

In this article, we created this Laravel Query project with Laravel 9. Creating a data table Laravel orderBy is very useful. We hope this orderBy project example will help you to understand the orderBy in Laravel 9.



Source link