PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label laravel-6. Show all posts
Showing posts with label laravel-6. Show all posts

Wednesday, November 16, 2022

[FIXED] How to get Current page Title of Relationship Model in Laravel?

 November 16, 2022     eloquent, laravel, laravel-6, laravel-6.2     No comments   

Issue

i have some fields in my database table, and i want to display title,description and keywords according to every page, Please let me know how i can display this. My database fields name are metatitle,metadesc,keyword

Here are my Controller code where i am displaying the property list...

    public function listtype($slug){
    $prtype= Listing::whereHas('proType',function($q) use($slug){
        $q->where('slug','like','%'.$slug.'%');
    })->paginate(50);
    return view('property-type',compact('prtype','title'));
}

Solution

You can do the following way:

 public function listtype($slug){
    $prtype= Listing::whereHas('proType',function($q) use($slug){
        $q->where('slug','like','%'.$slug.'%');
    })->with('proType')->paginate(50);
    dd($prtype); /** for checking **/ 
    return view('property-type',compact('prtype', $prtype));
 }


Answered By - Amit Senjaliya
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I store avatar(image file) through Auth/RegisterController while user registration?

 November 16, 2022     laravel, laravel-6, php     No comments   

Issue

My intention is to store a profile pic with user registration. I am using Laravel 6 User Authentication. I tried to do it in given method.

My html code is like this..

<form method="POST" action="{{ route('register') }}" enctype="multipart/form-data">
    @csrf
    <input type="text" name="name" placeholder="Name"><br>
        @error('name')
            <div>{{$message}}</div>
        @enderror
    <input type="file" name="avatar" placeholder="Profile photo"><br>
        @error('avatar')
            <div>{{$message}}</div><br>
    @enderror
</form>

I added validation in Auth/RegisterController.validator(). I added fields to store data to create function. RegisterController class is given below..

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'avatar' => ['mimes:jpeg,jpg,png,gif','required','max:10000']
        ]);
    }
    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'avatar' => file($data['avatar'])->store('avatars')
        ]);
    }
}

When I try to run this code, this error will occur

Error
Call to a member function store() on array
http://localhost:8000/register 

Note: I removed email, password and other fields just to reduce number of lines..


Solution

You can upload avatar with laravel default registration by doing following steps.

1) Add avatar field in your migration

$table->string('avatar');

2) Add avatar field in $filable in User model

protected $fillable = [
    'name', 'email', 'password', 'avatar',
];

3) Add avatar input field in register.blade.php

<div class="form-group row">
    <label for="avatar" class="col-md-4 col-form-label text-md-right">{{ __('Avatar') }}</label>

    <div class="col-md-6">
        <input id="avatar" type="file" class="form-control @error('avatar') is-invalid @enderror" name="avatar" value="{{ old('avatar') }}" required autocomplete="avatar" autofocus>

        @error('avatar')
            <span class="invalid-feedback" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>

4) Add avatar in the validator function for validation

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:6', 'confirmed'],
        'avatar' => ['required', 'image'],
    ]);
}

5) Handle file upload in create function

protected function create(array $data)
{
    $request = app('request');
    if ($request->hasfile('avatar')) {
        $avatar = $request->file('avatar');
        $filename = time() . '.' . $avatar->getClientOriginalExtension();

        //Implement check here to create directory if not exist already 

        Image::make($avatar)->resize(300, 300)->save(public_path('uploads/avatars/' . $filename));
    }

    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'avatar' => !empty($filename) ? $filename : 'default_avatar.png',
    ]);
}

6) Before you try to Run this make sure you have Image Class available in your controller, If you don't have image class you can include it in your project by doing following steps.

composer require intervention/image

Now open the config/app.php file. Add this to the $providers array.

Intervention\Image\ImageServiceProvider::class

Next add this to the $aliases array.

'Image' => Intervention\Image\Facades\Image::class

Now include Image class in User Controller like this

use Image;

Try to run your project, it should work fine.



Answered By - Umer Abbas
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to Count Value According to date in Laravel?

 November 16, 2022     eloquent, laravel, laravel-6, laravel-6.2, mysql     No comments   

Issue

I have multiple fields store in my database table, and there are followup field in my database and there are multiple dates store in this field. Now i want count data according to current date. But i am unable to do it.

I am getting same data multiple times, but i want in this format (Suppose there are 5 date store according to today date and they should be count 5, so that i can get the today followup clients )

Please let me know how i can do it.

Here are my controller code..

public function index()
 {
$lead=Lead::orderBy('created_at', 'desc')->get()
return view('admin.lead.index',compact('lead'));
 }

and here are my view file..

<div class="panel-heading">
@php
$mytime = Carbon\Carbon::now();
$checkdate=$mytime->toDateTimeString();
@endphp
<div class="panel-title">Today Follow Up's: 
    @foreach($lead as $lws)
        <span class="label label-warning">
            {{($lws->followup=$checkdate)}}
        </span>
    @endforeach
</div>
</div>

Solution

You can use below code to get only today's follow ups:

$lead=Lead::whereDate('followup', date('Y-m-d'))->get();

or to count the records:

$lead=Lead::whereDate('followup', date('Y-m-d'))->get()->count();


Answered By - Sehdev
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How I upload an image on laravel 6?

 November 16, 2022     file-upload, image, laravel-6, php, upload     No comments   

Issue

im trying to edit an image on laravel 6, but but it does not advance to next view, stays on the form view.

I have seen many tutorials of laravel 5.8 and 6. I can't make it work in any way

This is de controller:

 public function update(Request $request, $id)
{


    $validator = $request->validate([
       'titulo' => 'required | max:50', //campo obligatorio y máximo 50 caracteres
       'contenido' => 'required | max:150', 
       'imagen' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
    ]);

     $image_name = time().'.'.$request->imagen->getClientOriginalExtension();
     $request->image->move(public_path('images'), $image_name);


     $datos = array(
        'titulo' => $request->titulo,
        'contenido' => $request->contenido,
        'imagen' => $image_name,
    );

    Noticia::whereId($id)->update($datos);


    return redirect('/mostrar');
}

THis is Web.php file:

Route::get('/actualizar/{id}', 'crearNoticiaController@update')->name('actualizar');
Route::get('/editar/{id}', 'crearNoticiaController@edit')->name('editar');

this is form file:

<div class="subir-imagen">
    <form method="get" action="{{ route('actualizar', $noticia->id) }}"  enctype="multipart/form-data">
        @csrf   
        <div class="crear-titulo">
            <input class="titulo" type="text" name="titulo" placeholder="Escriba el titulo" value="{{$noticia->titulo}}">
        </div>

        <div class="crear-contenido">
            <textarea  class="ckeditor" name="contenido" placeholder="Escriba el contenido" >
                {{$noticia->contenido}}
            </textarea>
        </div>

        <table border="2">
            <tr>
                <td><img src="{{URL::to('/')}}/images/{{$noticia->imagen}}" alt="imagen" width="250" align="left"/></td>
            </tr>
        </table>



        <div class="form-group">
            <div class="col-md-6">
                <input type="file" class="form-control" name="imagen" />
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-6 col-md-offset-4">
                <input type="submit" class="btn btn-primary" value="Enviar" id="btn-enviar" />
            </div>
        </div>
    </form>
</div>

Thnaks for help


Solution

I've solved with this way:

In web.php I put patch instead get

Route::patch('/actualizar/{id}', 'crearNoticiaController@update')->name('actualizar');

In the edit blade I put: @method('PATCH')

And this is the update in the controller:

 public function update(Request $request, $id)
{


    $noticia = Noticia::findOrFail($id);


    $noticia->titulo = $request->get('titulo'); 
    $noticia->contenido = $request->get('contenido');
    $noticia->imagen = $request->file('imagen');
    $validator = $request->validate([
       'imagen' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
    ]);
    $imageName = time().'.'.request()->imagen->getClientOriginalExtension();
    request()->imagen->move(public_path('images'), $imageName);
    $noticia->imagen = $imageName;

    $noticia->update();

    return redirect('/mostrar'); //Redirigimos a la la vista para mostrar las noticias 


}


Answered By - Raúl Medina
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how can i fix this eror in laravel" 1005 Can't create table `englishcollage`.`role_user` (errno: 150 "Foreign key constraint is incorrectly formed"

 November 16, 2022     laravel, laravel-6, mysql, php     No comments   

Issue

i want to make a ACl migration in my Laravel project ... (version 6)

but i receive this annoying error :

General error: 1005 Can't create table English Collage.role_user (Errno: 150 "Foreign key constraint is incorrectly formed")")

English Collage is my database .

 Schema::create('permissions', function (Blueprint $table) {

          $table->increments('id');
          $table->string('title_fa'); // edit posts
          $table->string('title_en'); //edit-posts
          $table->timestamps();
      });


    Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title_fa'); // edit posts
        $table->string('title_en'); //edit-posts
        $table->timestamps();
    });

    Schema::create('role_user', function (Blueprint $table) {

            $table->Integer('role_id')->unsigned();

        $table->Integer('user_id')->unsigned();


            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade')->onUpdate('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');

    });

    Schema::create('permission_role', function (Blueprint $table) {

        $table->unsignedInteger('permission_id');

        $table->unsignedInteger('role_id');


        $table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade')->onUpdate('cascade');
        $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade')->onUpdate('cascade');

    });

and this is my users migration:

 Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('image')->nullable();
            $table->string('level')->nullable();
            $table->integer('age')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });

this structure work in laravel 5 but laravel 6 has issue with this

i tried big integer and unsigned big integer even i tested primary_key for role_user


Solution

To create Foreign key the data type for the child column must match the parent column exactly.

Since id is a bigIncrements i.e. unsigned big integer in users table then role_user.user_id must be unsignedbigInteger, not an unsignedInteger.

Change below in your role_user table

 $table->Integer('user_id')->unsigned();

to

 $table->unsignedBigInteger('user_id');


Answered By - Sehdev
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to set the route in <a> tag with user id in Laravel 6?

 November 16, 2022     laravel, laravel-6, laravel-blade     No comments   

Issue

This is My index blade where I want to click on the user name and it will redirect me on the edit user blade

@extends('layouts.admin')

        @section('content')
          <h1><b>Users</b></h1>
          <table class="table table-hover">
              <thead>
              <tr>
                  <th scope="col">#</th>
                  <th scope="col">Profile</th>
                  <th scope="col">Name</th>
              </tr>
              </thead>
              <tbody>
              @if($users)
                  @foreach($users as $user)
              <tr>
                  <td>{{$user->id}}</td>
                  <td><img height="25" src="{{$user->photo ? $user->photo->file:'No photo exist'}}"></td>


                <!-- Problem is here -->
                  <td><a href="{{route('admin.users.edit', $user->id)}}" style="text-decoration: none"> 
                {{$user->name}}</a></td>


*it through an exception* 

**Route [admin.users.edit] not defined**       
              </tr>
                  @endforeach
                  @endif
              </tbody>
          </table>
        @endsection

If I use the url() method {{url('admin/users/edit',$user->id)}} like this it will redirect me as admin/users/edit/1 but my route is set as admin/users/1/edit. How can I open this route?


Solution

I will not suggest to use admin/users/1/edit even then if you want to use this then

Change

{{url('admin/users/edit',$user->id)}}

to

{{url('admin/users/'.$user->id.'/edit')}}

Reference:

Laravel ->URL Generation -> Generating Basic Url



Answered By - Sehdev
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] When trying to insert data got this error msg Add [name] to fillable property to allow mass assignment on [App\Suitspecialist]

 November 16, 2022     get, laravel, laravel-6, post     No comments   

Issue

Can anyone explain it to me why controller portion throwing error?

Here is my MODEL:

class Suitspecialist extends Authenticatable
{
    use Notifiable;
    protected $guard = 'suitspecialist';
    protected $fillable = [
        'name', 'email', 'password',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];
}

CONTROLLER

This portion throws an error

Add [name] to fillable property to allow mass assignment on [App\Suitspecialist].

protected function createSuitspecialist(Request $request)
{
    $this->validator($request->all())->validate();
    Suitspecialist::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => Hash::make($request->password),
    ]);
    return redirect()->intended('login/suitspecialist');
}

Solution

When you try to fill severeal properties on a model using a method like fill, create or update, you need to specify the fields that can be filled this way. This is call "mass assignment".

This is an Eloquent security implemented to avoid that you store data you don't want to.

In your model, use the guarded or fillable attributes to specify which properties you want or don't want to register use mass assignment. These properties accepts an array.

Look in the Laravel documentation it is well explained : https://laravel.com/docs/7.x/eloquent#mass-assignment



Answered By - Benjamin Masi
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to create a template view table tag without repeating table tags on every file

 November 16, 2022     laravel, laravel-6, laravel-7, laravel-views     No comments   

Issue

I'm developing a system which has many tables so I have to repeat the writing of table tags on all the files which display a table Here is what I'm doing on every file which have to display table

On Countries table:

  <table class="table table-striped table-hover table-sm" id="table">
                        <thead class="text-uppercase text-center bg-primary">
                        <tr class="text-white">
                            <th scope="col">Name</th>
                            <th scope="col">Slug</th>
                            <th scope="col">Population</th>
                            <th scope="col">Region</th>
                            <th scope="col">Cities</th>
                            <th scope="col">Descriptions</th>
                            <th scope="col" >Actions</th>
                        </tr>
                        {{ csrf_field() }}
                        </thead>
                        <tbody>
                            @foreach ($countries as $country)
                                <tr>
                                    <td class="text-left">{{$country->name}}</td>
                                    <td class="text-center">{{$country->slug}}</td>
                                    <td class="text-right">{{$country->population}}</td>
                                    <td class="text-center">{{$country->region->name}}</td>
                                    <td class="text-center">{{$country->city_count}}</td>
                                    <td class="text-left">{{$country->desc}}</td>
                                    <td class="text-center">
                                        <div class="btn-group">

                                            @can('country-update')
                                                <a class="btn btn-primary btn-sm mr-2" href="{{route('location.countries.edit',$country)}}" title="Edit"><i class="fa fa-edit"></i></a>
                                            @endcan

                                            @can('country-delete')
                                                <form class="form-delete" method="post" action="{{route('location.countries.destroy',$country)}}">
                                                    @method('DELETE')
                                                    @csrf
                                                    <button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure?')"><i class="fa fa-trash-alt"></i></button>
                                                </form>
                                            @endcan
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>

then on the cities I'll do the same but with different table head names and table data

 <table class="table table-striped table-hover table-sm" id="table">
                    <thead class="text-uppercase text-center bg-primary">
                    <tr class="text-white">
                        <th scope="col">Name</th>
                        <th scope="col">Slug</th>
                        <th scope="col">Country</th>
                        <th scope="col">Descriptions</th>
                        <th scope="col" >Actions</th>
                    </tr>
                    {{ csrf_field() }}
                    </thead>
                    <tbody>
                        @foreach ($cities as $city)
                            <tr>
                                <td class="text-left">{{$city->name}}</td>
                                <td>{{$city->slug}}</td>
                                <td class="text-center">{{$city->country->name}}</td>
                                <td class="text-left">{{$city->desc}}</td>
                                <td class="text-center">
                                    <div class="btn-group">

                                        @can('city-update')
                                            <a class="btn btn-primary btn-sm mr-3" href="{{route('location.cities.edit',$city)}}" title="Edit"><i class="fa fa-edit"></i></a>
                                        @endcan

                                        @can('city-delete')
                                            <form class="form-delete" method="post" action="{{route('location.cities.destroy',$city)}}">
                                                @method('DELETE')
                                                @csrf
                                                <button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure?')" title="delete"><i class="fa fa-trash-alt"></i></button>
                                            </form>
                                        @endcan
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table> 

but I wat to have a template where I'll only populate table head rows and table body something like this

<div class="table-responsive">
    <table class="table table-striped table-hover table-sm" id="table">
        <thead class="text-uppercase text-center">
        <tr>
            //Dynamic table heads
            @if(!is_null($rows))
                @foreach($rows as $row)
                    {{$row}}
                @endforeach
            @endif
        </tr>
        </thead>
        <body>
            //Dynamic table body
            @if(!is_null($datas))
                @foreach($datas as $data)
                    {{$data}}
                @endforeach
            @endif
        </tbody>
    </table>
    <!-- end table -->
</div>

What is the best way to accomplish this


Solution

You can use Blade component for that. One of approaches in Laravel 7 is to use Blade class component. Link to official Blade components docs: https://laravel.com/docs/7.x/blade#components

You can create a generic table component using artisan command:

php artisan make:component Table

Component class

Your component could look like that:

<?php 

namespace App\View\Components;

use Illuminate\View\Component;

class Table extends Component
{
    /**
     * Array of table heading strings
     *
     * @var array
     */
    public $headings;

    /**
     * Table rows
     *
     * @var array
     */
    public $rows;

    /**
     * Create the component instance.
     *
     * @param  string  $type
     * @param  string  $message
     * @return void
     */
    public function __construct($headings, $rows)
    {
        $this->headings = $headings;
        $this->rows = $rows;
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\View\View|string
     */
    public function render()
    {
        return view('components.table');
    }
}

Component view

Now when you have component class, you have to prepare the component view. You will found it in /resources/views/components/table.blade.php.

<div class="table-responsive">
    <table class="table table-striped table-hover table-sm" id="table">

        //Dynamic table heads
        @if($headings)
        <thead class="text-uppercase text-center">
            <tr>
                @if($rows))
                    @foreach($rows as $row)
                        <th>{{$row}}</th>
                    @endforeach
                @endif
            </tr>
        </thead>
        @endif

        <tbody>
            //Dynamic table body
            @foreach($rows as $row)
                <tr>
                    // Render each item from row
                    @foreach($row as $item)
                        <td>{{$item}}</td>
                    @endforeach
                </tr>
            @endif
        </tbody>
    </table>
    <!-- end table -->
</div>

Now you can use your component in your views:

<x-table :headings="['foo', 'bar']" 
         :data="[['foo1', 'bar1'], ['foo2', 'bar2']]" class="mt-4"/>


Answered By - Michael Dojčár
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to stop GET on a POST route (laravel)

 November 16, 2022     laravel, laravel-6, laravel-7     No comments   

Issue

I'm new to laraval. I got this POST route but if someone try the address on the browser it become a GET route and laravel throw a error. Is there a way to throw a 404 page for a GET request on POST route.

Route::post('/step2Validate', 'StepController@step2Validate');

If this route is access as GET "The GET method is not supported for this route. Supported methods: POST." error is given.


Solution

Try this:

Route::get('/step2Validate', function() { 
    abort(404); 
    }
);


Answered By - Dimitri Mostrey
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to retrieve limited number of related model and sort collection by related model in laravel?

 November 16, 2022     laravel, laravel-6, relationship     No comments   

Issue

I have 3 model Shop model, Product model, Picture model

I want to retrieve a collection of shops with last 3 Product model with their pictures and sort my collection based on newest product. I tried leftjoint and joint in laravel 6 to be able to sort the result but i get all shops`product (i only need last 3 product for each shop),

when I use joint I cant retrieve product pictures I also have tried “with” method in laravel , I couldnt sort the result based on product.creatred_at and also i get all related product in this method too.(as i mentioned i need the last 3 product)

class Shop extends Model
{
    public function products()
    {
        return $this->hasMany('App\Product');
    }
}

class Product extends Model
{

    public function shop()
    {
        return $this->belongsTo('App\Shop');
    }

    public function pictures()
    {
        return $this->morphMany('App\hPicture', 'pictureable');
    }

}


Shop::select('shops.*', 'products.id', 'products.shop_id', 'products.name as pname', 'products.user_id', 'products.code', 'products.price')
            ->with(['pictures', 'products.pictures'])
            ->leftjoin('products', function ($leftJoin) {
                $leftJoin->on('shops.id', '=', 'products.shop_id');
            });
            $dataList = $dataList->orderBy($field, $order);
            $dataList = $dataList->paginate(5)->appends(['sortField' => $field, 'sortOrder' => $order]);

the table layout for product and shop model is:

 Schema::create('shops', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('slug');
        $table->string('phone')->nullable();
        $table->string('address')->nullable();  
        $table->timestamps();
        $table->string('description')->nullable();
        $table->uuid('uuid');
    });
 Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('shop_id')->unsigned();
            $table->foreign('shop_id')->references('id')->on('shops');
            $table->string('name');
            $table->string('code');
            $table->string('slug');
            $table->integer('price');
            $table->uuid('uuid');
            $table->timestamps();
        });

Solution

There are only 2 ways of resolving this:

  1. Either you pull in all products, and trim them in the end(advisable only if not too many products per shop):
$shops = Shop::with(['products' => function($subQuery) { 
    $subQuery
        ->with('pictures') //Running in scope of product, also load each product's pictures
        ->orderBy('created_at', 'desc');
}])
->get();
foreach ($shops as $shop) {
   $shop->setRelation('products', $shop->products->take(3));
}

NOTE:

You will load every single product that is linked to the shops you load. You could get memory issues with this.

  1. Take only what you need, but introduce a n+1 query issue(advisable only with small quantities of $shops:
$shops = Shop::get();
foreach ($shops as $shop) {
    $shop->load([
        'products' => function($query) {
            $query
                ->orderBy('created_at', 'desc')
                ->limit(3)
                ->get();
    }]);
}

NOTE:

N+1 query problem: You are performing a new query for each shop, so if you have a million shops, it will be a million extra queries.

EDIT: (answering comment question)

Q: How can i sort $shops based on their latest product created_at field?

$sortedShops = $shops->sortBy(function ($shop, $key) {
    return $shop->products->first()->created_at;
})->values()->all();

sortBy is called on the collection(not uery). It allows you to go over each element(in this case shops) and use each object. Please do note that this function will fail if you have no products linked to the shop.

The ->values()->all() at the end makes sure that when you convert your shops to json, you will create an array, and not an object in js.

Source: https://laravel.com/docs/7.x/collections#method-sortby

EDIT: (deleted original answer as it did not work)

  • Previous answer does not work, because limit(3) will limit the total amound of products loaded, in stead of 3 products per shop(my bad).


Answered By - Techno
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to retrieve Json data type data in SQL using a where condition in LARAVEL

 November 16, 2022     eloquent, laravel, laravel-5, laravel-6, laravel-7     No comments   

Issue

Question : How to retrieve Json data type data in SQL using a where condition in LARAVEL?

I want to display all the order that contains order->Product->user->id === 1

{
"currentUserID": 1,
"currentUserName": "Mohamed Naalir",
"order": [
    {
        "id": 26,
        "Product": [
            {
                "id": 4,
                "name": "Araliya Rice",
                "desription": "Araliya Rice",
                "salePrice": 500,
                "category": "Rice",
                "user": {
                    "id": 1,
                    "name": "Mohamed Naalir",
                }
            }
        ],
    },
    {
        "id": 27,
        "Product": [
            {
                "id": 2,
                "name": "white sugar",
                "desription": "aaa",
                "salePrice": 100,
                "category": "Sugar",
                "user": {
                    "id": 5,
                    "name": "Mohamed Sharaf",
                }
            }
        ],
    }
]

}


Solution

json where clauses

 $orders = DB::table('orders')
            ->whereJsonContains('Product', [['user' => ['id' => 1]]])
            ->get();


Answered By - Mohamed Raza
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to use logical operator in a laravel validation?

 November 16, 2022     laravel, laravel-6, laravel-validation     No comments   

Issue

I created a working validator for checking the phone to my AppServiceProvider.php

Validator::extend('phone', function ($attribute, $value, $parameters, $validator) {
    return preg_match('/^09[0-9]{9}$/', $value);
});

Now this time I want to validate for my username that accepts either email or phone. Something like below.

'username' => 'email OR phone'

As expected that code above will not work. Somebody knows how to achieve? I really needing this for my project.


Solution

How about you create another validator for username so you can perform logical operator.

Validator::extend('username', function ($attribute, $value, $parameters, $validator) {
    $emailPattern = '/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD';

    return preg_match('/^09[0-9]{9}$/', $value) || preg_match($emailPattern, $value);
});

Now you can use it.

'username' => 'username'


Answered By - tempra
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to pass radio button value as route parameter in Laravel?

 November 16, 2022     html, javascript, jquery, laravel, laravel-6     No comments   

Issue

I want to pass the selected radio button value as a parameter with Laravel route.

My Route is:

Route::resource('/datas','DataController');

From this route, I am aiming to call localhost:8000/datas/{data}

My data.blade.php is:

<form id="dataform" action="{{ route('datas.show')}}" method="GET">
   <table class="table">
      <tr>
         <th>Select bullet</th>
         <th>SL NO</th>
         <th>Name</th>
         <th>Age</th>
      </tr>
      @foreach ($datas $key => $data)
         <tr>
            <td><input type="radio" id="data{{$data->id}}" name="data" value={{$data->id}}></option></td>
            <td>{{$key}}</td>
            <td>{{$data->name}}</td>
            <td>{{$data->age}}</td>
         </tr>
      @endforeach
   </table>
   <button type="submit" id="edit_submit" class="btn btn-default">Show</button>                    </form>

My show function will be...


public function show($id)
   {
      //Code to showing data and redirect to show page
   }

I want to get value of this radio button(given below).

<td><input type="radio" id="data{{$data->id}}" name="data" value={{$data->id}}>

and include it as a parameter with the Form action below

<form id="dataform" action="{{ route('datas.show')}}" method="GET">

Solution

I have made some changes to this code. Changed button to anchor tag. So my blade.php is:-

   <table class="table">
      <tr>
         <th>Select bullet</th>
         <th>SL NO</th>
         <th>Name</th>
         <th>Age</th>
      </tr>
      @foreach ($datas $key => $data)
         <tr>
            <td><input type="radio" id="data{{$data->id}}" name="data" value={{$data->id}}></option></td>
            <td>{{$key}}</td>
            <td>{{$data->name}}</td>
            <td>{{$data->age}}</td>
         </tr>
      @endforeach
   </table>
   <a  href="javascript:showfunction()" id="showlink" class="btn btn-default">Show</a>

and I added a javascript function too.

<script>
    function showfunction(){
       var id = document.querySelector('input[name = "data"]:checked').value;
       var url = '{{route("admin.questions.show",":id")}}';
       url=url.replace(':id',id);
       document.location.href=url;
    }
</script>


Answered By - Hisham U
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to get records with its related data in intermediate table

 November 16, 2022     laravel-6, postman     No comments   

Issue

I have two model, Category and Brand with many to many relation

in Category model

public function brands()
    {
        return $this->belongsToMany(Brand::class, 'brand_category', 'category_id', 'brand_id');
    }

and in brand model

    public function categories()
    {
        return $this->belongsToMany(Category::class, 'brand_category','brand_id','category_id' );
    }

how can i get brands with specific category id like json below

{
    "data": [
        {
            "brand_id": 1,
            "name": "Sony",
            "description": null,
            "logo": null,
            "is_active": true,
            "created_at": "2020-04-08 15:19:44",
            "updated_at": "2020-04-08 15:19:44",
            "deleted_at": null,
            "pivot": {
                "category_id": 1,
                "brand_id": 1
            }
        },
        {
            "brand_id": 2,
            "name": "Lg",
            "description": null,
            "logo": null,
            "is_active": true,
            "created_at": "2020-04-08 15:19:44",
            "updated_at": "2020-04-08 15:19:44",
            "deleted_at": null,
            "pivot": {
                "category_id": 1,
                "brand_id": 2
            }
        }
    ],
    "success": true,
    "error": {
        "code": 200,
        "data": []
    },
    "message": ""
}

i want to find a way without changing relations in models by wherePivot...


Solution

this should do.

return Category::find($categoryId)->brands;


Answered By - Andy Song
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to validate a field that must be false in laravel form request

 November 16, 2022     laravel-6     No comments   

Issue

I want to set ('is_color' = false) if ('is_variation' = true) in form request

        $rules  = [
            'is_color'                      =>  'nullable|boolean',
            'is_guarantee'                  =>  'nullable|boolean',
            'is_variation'                  =>  'nullable|boolean',
        ];

Solution

It seems not related to the validation, What I found out is you want set is_color due to is_variation's value, so you can validate just is_variation and set is_color. But you can validate these parameter related to each other with make a method named withValidator in your form request. For more information you can see below link: With Validator

Or you can make custom rule validation : Custom Validation in laravel



Answered By - Mehrdad Saami
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to populate a field in a laravel model even if the field it's not in the form request

 November 16, 2022     laravel, laravel-6, model, php     No comments   

Issue

sorry for the messy title.

So, I have a basic User model and I'm trying to register a new user, the thing is one of my field in the users table is a 'screen_name' that I would like to be filed automatically with the the first 'word' from the name attribute.

How can I do that?

I've tried

public function setScreenNameAttribute($value){
   return 'MyFirstName';
}

But as I understand, the set***Attribute will only be fired if I have this field in my form request, but I don't want the user to fill this field I want the model to do that by it's own.


Solution

Model

public function setScreenNameAttribute($value)
    {
        $this->attributes['screen_name'] = strtolower(strtok($value, ' ')); // First name from the full name as screen name
    }

Controller

$user->screen_name = 'John Smith'; // your request value goes here - $request->full_name; 

You don't need to have a field for that in the form.

Hope this helps.

Let me know if doesn't work.


Updated / Anohter solution.

protected $attributes = array(
  'screen_name' => 'Your name' // Any values
);

public function __construct(array $attributes = array())
{
    $this->setRawAttributes(array(
      'screen_name' => strtolower(strtok($attributes->first_name, ' '));
    ), true);
    parent::__construct($attributes);
}


Answered By - Kaushik Thakkar
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to eager load only 1 result from many to many relationship Laravel

 November 16, 2022     eloquent, laravel, laravel-6     No comments   

Issue

How can I eager load only one from many to many relationship?

I have two models Application & Applicant

Models\Application.php

public function applicants() {
    return $this->belongsToMany(Applicant::class);
}

public function oneApplicant() {
    return $this->applicants()->first();
}

I'm wanted to paginate on the applications and want to load only one applicant (if they have.)

return Application::stage( $stages )
->stagenot($stageNot)
->refered( $refered, $term )
->with(['oneApplicant'])
->orderBy('created_at','desc')->paginate( $count );

But it isn't working. Getting the first result like this return $this->applicants()->first() will produce an error Call to undefined method Illuminate\Database\Query\Builder::with()

If I also put a limit instead of first return $this->applicants()->limit(1) it will only show one applicant to the last collection.

I also tried to modify the query directly on eager loading call to get the first row

return Application::with(['applicants',  => function( $query ) {
        $q->first();
    }])->orderBy('created_at','desc')->paginate( $count );

But the result is the same as adding a limit(1) on directly on the relation, it will only add one applicant to the last item from collection and the other item have empty array value

Can anybody help :)

Thanks


Solution

I realized its too complex to achieve it myself and ended up using the eloquent-eager-limit package from staudenmeir (big thanks to him, save me hours of work :) )

here's my model

class Application extends BaseModel {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;

    public function applicants() {
        return $this->belongsToMany(Applicant::class);
    }

    public function oneApplicant() {
        return $this->applicants()->limit(1);
    }
}

Then I was able to use it on my controller

return Application::stage( $stages )
    ->stagenot($stageNot)
    ->refered( $refered, $term )
    ->with([
        'oneApplicant',
        'oneApplicant.onePhone:model_id,number',
        'oneApplicant.oneAddress:model_id,state'
    ])->orderBy('created_at','desc')->paginate( $count );



Answered By - SymmetricsWeb
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to use One view with Multiple Guards Laravel

 November 16, 2022     laravel, laravel-5, laravel-6, laravel-7, laravel-views     No comments   

Issue

I have multiple guards in my system

Admin
User

Admin and User both can add the Organizations details but they have different template layout. What i'm doing now i create views of each guard like this

views
  user
    organizations
       index.blade.php
       _form.blade.php
       create.blade.php
       edit.blade.php
  admin
    organizations
       index.blade.php
       _form.blade.php
       create.blade.php
       edit.blade.php

Now i want to create one views which can be used by multiple guards with different layouts

views
   organizations
      index.blade.php
      _form.blade.php
      create.blade.php
      edit.blade.php

Solution

From the Laravel Blade Documentation:

If needed, you may specify the authentication guard that should be checked when using the @auth and @guest directives:

@auth('admin')
    // The user is authenticated...
@endauth

@guest('admin')
    // The user is not authenticated...
@endguest


Answered By - mchljams
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to update all rows of a table without retrieving them in Laravel?

 November 16, 2022     eloquent, laravel, laravel-6, mysql     No comments   

Issue

I am trying to update all rows inside one of my database tables but I am receiving the following error:

Non-static method Illuminate\Database\Eloquent\Model::update() should not be called statically

I am doing this inside a migration:

public function up()
{
    Schema::table('rooms', function (Blueprint $table) {
        $table->json('beds')->nullable();
    });

    Room::update([
        'beds' => ['One King', 'Two Doubles']
    ]);

    Schema::table('rooms', function (Blueprint $table) {
        $table->json('beds')->nullable(false)->change();
    });
}

I am adding a json column 'beds' to my existing table 'rooms' and want to set a default value of ['One King', 'Two Doubles'], I am wondering if I can do it directly in the query without loading the models.

I made up the following solution, but it feels kinda "hacky":

// All id's are bigger than 0
Room::where('id', '>', 0)->update([
    'beds' => ['One King', 'Two Doubles']
]);

Does anyone know of another way to do update all rows without the where statement?


Solution

You can call the static query() method on the model:

// ::query() return an instance of \Illuminate\Database\Eloquent\Builder
Room::query()->update([
  'beds' => ['One King', 'Two Doubles']
]);


Answered By - Brian Lee
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to use One Laravel Controller with Multiple Guard instead of Duplicating the Controller

 November 16, 2022     laravel, laravel-6, laravel-7, laravel-authentication, laravel-authorization     No comments   

Issue

I have two Guards

Admin
User

Also i have created controllers where user can manage his own data and admin can also manage user data. So i created two Controllers

Controllers
    Admin
        EducatonBackgroundController
    User
        EducationBackgroundController

In User/EducationBackgroundController i have this function which fetch education background of a current logged user and display on the user view

 public function index(Education $education)
    {
        try {
            $educations = $education->where('user_id',$this->userLoggedID())->with('organization','program','country','city')->get();
            return view('users.education.index',compact('educations'));
        }
        catch (Exception $e) {
            abort(404);
        }
    }

In Admin/EducationBackgroundController i have this function which fetch education background of all users and display on the admin view

 public function index(Education $education)
    {
        try {
            $educations = $education->with('organization','program','country','city','user')->get();
            return view('admin.users.education.index',compact('educations'));
        }
        catch (Exception $e) {
            abort(404);
        }
    }

From observation these functions are similar but differ on view return and data fetch.

So How can i create a one Controller which can be used by both Admin and User guards instead of duplicate Controller and View for both Guards.


Solution

I did something similar by adding a second set of routes, like this:

<?php

    Route::middleware(['auth:admin_api'])->group(function () {
        Route::prefix('admin')->group(function () {
            Route::name('api.admin.')->group(function () {

                ////////////////////////////////////////////////////////////
                /// PLACE ADMIN API ROUTES HERE ////////////////////////////
                ////////////////////////////////////////////////////////////
                Route::apiResource('test','App\Http\Controllers\API\MyController');
                ////////////////////////////////////////////////////////////
            });
        });
    });

    Route::middleware(['auth:api'])->group(function () {
        Route::name('api.')->group(function () {
            ////////////////////////////////////////////////////////////
            /// PLACE PUBLIC API ROUTES HERE ///////////////////////////
            ////////////////////////////////////////////////////////////
            Route::apiResource('test', 'App\Http\Controllers\API\MyController');
            ////////////////////////////////////////////////////////////
        });
    });

So when an admin user goes to admin/test, it uses the admin auth guard, and when a normal user goes to /test it uses the standard auth guard. Both of these use the same controller.

I then created a base controller for my app. Here is how I determined with guard is being used to access the route in the constructor:

<?php


use Illuminate\Http\Response;
use App\Http\Controllers\Controller;

class BaseController extends Controller
{
    protected $user;

    protected $isAdmin = false;

    public function __construct()
    {
        if(Auth::guard('admin_api')->check()) {
            $this->user = Auth::guard('admin_api')->user();
            $this->isAdmin = true;
        } elseif(Auth::guard('api')->check()) {
            $this->user = Auth::guard('api')->user();
            $this->isAdmin = false;
        } else {
            return response()->json([
                'message' => 'Not Authorized',
            ], 401);
        }
    }



Answered By - mchljams
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing