Showing posts with label laravel. Show all posts
Showing posts with label laravel. Show all posts

how to add translation in foreach list into laravel blade

 To add translations to a foreach loop in Laravel Blade, you can use the @lang directive to translate each item in the loop. Here is an example:

@foreach($items as $item)
    <li>@lang('messages.' . $item->name)</li>
@endforeach

In this example, the items variable contains a collection of objects with a name attribute. The @lang directive is used to translate each item's name by passing the translation key to the trans function. The translation key is constructed using the dot notation and the name attribute value of each item.

Assuming that you have defined the translations in your language files under the messages namespace, the @lang directive will automatically translate the item's name based on the current locale. If a translation is not available for the current locale, the original string will be returned.

Laravel create a api with sactum

To create a Laravel API with Sanctum, you can follow these steps:

Install Laravel Sanctum: 


composer require laravel/sanctum

Publish the Sanctum configuration and migration files:


php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

Run the Sanctum migrations:


php artisan migrate

Add the HasApiTokens trait to your User model:

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
   
    // ...
}


Register the Sanctum middleware in your Kernel class:


protected $middlewareGroups = [
    // ...
    'api' => [
        EnsureFrontendRequestsAreStateful::class,
        'throttle:60,1',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreAuthorized::class,
    ],
];


Generate a new API token for your authenticated user:


$token = $user->createToken('API Token')->plainTextToken;

Use the generated API token to authenticate your API requests:


Authorization: Bearer {api_token}

You can now create your API routes and controllers as usual. To protect a route with Sanctum, you can use the auth:sanctum middleware:


Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});


CRUD EXAMPLE

Next, let's create a Product model and migration file to store our product data. Run the following commands to create them:


php artisan make:model Product -m

This will create a Product.php model file and a migration file for the products table.

In the migration file, add the following code to define the columns for the products table:

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->text('description');
        $table->decimal('price', 8, 2);
        $table->timestamps();
    });
}

Next, run the migration to create the products table:


php artisan migrate


Now, let's create a ProductController to handle the CRUD operations. Run the following command to generate a new controller:

php artisan make:controller ProductController --api

This will create a new ProductController.php file in the app/Http/Controllers folder with boilerplate code for a RESTful API.

Add the following code to the ProductController to define the CRUD methods:

use App\Models\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function index()
    {
        $products = Product::all();
        return response()->json($products);
    }

    public function store(Request $request)
    {
        $product = Product::create($request->all());
        return response()->json($product);
    }

    public function show(Product $product)
    {
        return response()->json($product);
    }

    public function update(Request $request, Product $product)
    {
        $product->update($request->all());
        return response()->json($product);
    }

    public function destroy(Product $product)
    {
        $product->delete();
        return response()->json(null, 204);
    }
}


Next, let's protect our API routes with Sanctum. In the routes/api.php file, add the following code to define the routes and apply the auth:sanctum middleware:

use App\Http\Controllers\ProductController;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->group(function () {
    Route::apiResource('products', ProductController::class);
});

Now, to test our API, we can use tools like curl or Postman to send HTTP requests to the API endpoints.


For example, to create a new product, we can send a POST request to http://localhost:8000/api/products with a JSON payload:

{
    "name": "Product A",
    "description": "This is product A",
    "price": 19.99
}

To retrieve all products, we can send a GET request to http://localhost:8000/api/products.

To update a product, we can send a PUT request to http://localhost:8000/api/products/{product_id} with a JSON payload:

{
    "name": "Product A (updated)",
    "description": "This is product A (updated)",
    "price": 29.99
}


To delete a product, we can send a DELETE request to http://localhost:8000/api/products/{product_id}.


I hope this helps you get started with creating a Laravel API with Sanctum.




Laravel mPdf add custom font

  1. Download the font you want to use and save it in your Laravel project's "public/fonts" directory.

  2. Open your controller or create a new one and import the mPDF class at the top of your file:


use Mpdf\Mpdf;

Create a new instance of the mPDF class:


$pdf = new Mpdf();

Use the "AddFont" method to add the font to mPDF. You'll need to provide the path to the font file, the font name, and any additional options you want to set. Here's an example


$font_path = public_path('fonts/YourFontName.ttf');

$pdf->AddFont('YourFontName', '', $font_path);



Replace "YourFontName" with the actual name of the font file (without the ".ttf" extension).

You can also set additional options such as the font weight and style



$pdf->AddFont('YourFontName', 'B', $font_path, 32);


  1. In this example, the font weight is set to "B" (bold) and the font size is set to 32.

  2. Use the "SetFont" method to set the font you just added as the default font:



$pdf->SetFont('YourFontName', '', 12);


  1. In this example, the font size is set to 12.

  2. Add content to your PDF as usual using the mPDF class.

  3. Generate the PDF and return it as a download or stream:


$pdf->Output('YourFileName.pdf', 'D');


  1. Replace "YourFileName.pdf" with the name you want to give your PDF file, and "D" to download the file.

That's it! You have successfully added a custom font to mPDF in your Laravel project.



Laravel how to import excel/xls file into database

Sure, here are the steps to import an Excel file into Laravel:

  1. First, you need to install the "maatwebsite/excel" package using Composer. You can do this by running the following command in your terminal:

    composer require maatwebsite/excel

  2. Next, create a new controller or use an existing one to handle the file upload and import process.

  3. In your controller, you'll need to include the following classes at the top: 


use Maatwebsite\Excel\Facades\Excel;
use App\Imports\YourImportClass;



Create a function to handle the file upload and import process. This function should accept a file parameter and use the Excel class to read the file and pass it to your import class. Here's an example:

public function import(Request $request)
{
    $file = $request->file('file');

    Excel::import(new YourImportClass, $file);

    return redirect()->back()->with('success', 'File imported successfully!');
}



Create an import class to handle the actual import process. This class should extend the "Maatwebsite\Excel\Concerns\ToCollection" class and implement the "toArray()" method. This method should return an array of data that will be imported into your database. Here's an example:


use Maatwebsite\Excel\Concerns\ToCollection;

class YourImportClass implements ToCollection
{
    public function collection(Collection $rows)
    {
        foreach ($rows as $row) {
            // process each row and save data to database
        }
    }
}




Finally, create a view with a form to allow users to upload the Excel file. The form should have an input field with the name "file" and the "enctype" attribute set to "multipart/form-data". Here's an example:


<form method="POST" action="{{ route('import') }}" enctype="multipart/form-data">
    @csrf
    <input type="file" name="file">
    <button type="submit">Import</button>
</form>



That's it! With these steps, you should now be able to import Excel files into your Laravel application.

Laravel one to many query example

 In Laravel, you can use Eloquent ORM to define and perform one-to-many relationships between tables in your database. Here's an example of how to perform a one-to-many query using Eloquent:

Suppose you have two tables: users and posts. Each user can have multiple posts, but each post belongs to only one user. The users table has a primary key column id, and the posts table has a foreign key column user_id that references the id column in the users table.

To define the relationship between the two tables in Laravel, you would create two models: User and Post. In the User model, you would define a posts() method that uses the hasMany method to define the one-to-many relationship:


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}


In the Post model, you would define a user() method that uses the belongsTo method to define the inverse of the one-to-many relationship:


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}



In the Post model, you would define a user() method that uses the belongsTo method to define the inverse of the one-to-many relationship:


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}



With this relationship defined, you can now perform a one-to-many query to retrieve all posts for a given user:



$user = User::find(1);
$posts = $user->posts;



In this example, we retrieve the User model with an id of 1 using the find() method, and then access the posts relationship using the posts method we defined earlier. This will return a collection of Post models that belong to the user with an id of 1.

You can also eager load the posts relationship to reduce the number of database queries:


$user = User::with('posts')->find(1);
$posts = $user->posts;


In this example, we use the with() method to eager load the posts relationship, which will retrieve all posts for the user with an id of 1 in a single query.

Laravel using the Yajra DataTables package

 To display a user list in Laravel using the Yajra DataTables package, you can follow these steps:

  1. Install the Yajra DataTables package: Run the following command to install the Yajra DataTables package:

composer require yajra/laravel-datatables-oracle:^9.0


  1. Add the Yajra DataTables service provider: Open the config/app.php file and add the following line to the providers array:
Yajra\DataTables\DataTablesServiceProvider::class,



  1. Publish the Yajra DataTables configuration file: Run the following command to publish the Yajra DataTables configuration file:
php artisan vendor:publish --tag=config



This will create a datatables.php file in the config directory.

  1. Create a route to fetch the users data: In your routes/web.php file, create a route to fetch the users data using the Yajra DataTables package:
Route::get('users', 'UserController@index')->name('users.index');


  1. Create a controller: Create a UserController controller by running the following command:

php artisan make:controller UserController


  1. Define the index method: In the UserController controller, define the index method to fetch the users data and return it as a JSON response:

use App\User;
use DataTables;

public function index()
{
$users = User::select(['id', 'name', 'email']);

return DataTables::of($users)->make(true);
}



This method selects only the id, name, and email fields from the users table and passes them to the DataTables::of() method to create a DataTable instance.

  1. Create a view: Create a users.blade.php view file in the resources/views directory and add the following code:
@extends('layouts.app')

@section('content')
<table id="users-table" class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
</table>
@endsection

@push('scripts')
<script>
$(function() {
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: '{{ route("users.index") }}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
{ data: 'email', name: 'email' },
]
});
});
</script>
@endpush
    


This view extends the layouts.app layout and defines a table with an ID of users-table. It also includes a JavaScript block to initialize the DataTable instance using the server-side processing mode and the route to fetch the users data.

  1. Create a route to display the view: In your routes/web.php file, create a route to display the users.blade.php view:

Route::get('/', function () {
return view('users');
});



  1. Include the DataTables assets: In your layouts/app.blade.php file, include the DataTables CSS and JavaScript assets:
<!DOCTYPE html>
<html>
<head>
<title>@yield('title')</title>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css">
</head>
<body>
<div




.

how to call ssh from vs code

 To call SSH from VS Code, you can use the built-in Remote Development extension. This extension allows you to open a remote folder or works...